【问题标题】:Null pointer exception while trying to upload a CSV file to the server尝试将 CSV 文件上传到服务器时出现空指针异常
【发布时间】:2018-04-27 02:00:02
【问题描述】:

我正在尝试将 csv 文件上传到服务器。以下是我的 html 代码:

<form method="post" id="uploadCSV" enctype="multipart/form-data">
    File to upload: <input type="file" id="uploadfile" name="file" accept="text/csv">

 <input type="submit" value="Upload" id="uploadcsv" ng-click="uploadCSV()"> Press here to upload the file!
</form>

还有我的 JS:-

 $scope.uploadCSV  = function() 

{

        var fileToLoad = document.getElementById("uploadfile").files[0];

        var csvreporturl = "/api/oel/csv";
        $http.post(csvreporturl, fileToLoad).then(function(response, status) {
           console.log("posted:",response);
        });

  }

最后是 Spring Boot 中的控制器:-

@RequestMapping(value = "/api/oel/csv", method = RequestMethod.POST)

 String uploadFileHandler(@RequestBody MultipartFile fileToLoad) throws FileNotFoundException, IOException

{

        String name = fileToLoad.getName();
        if (!fileToLoad.isEmpty()) {
            try {
                byte[] bytes = fileToLoad.getBytes();

                // Creating the directory to store file
                //String rootPath = System.getProperty("catalina.home");
                File dir = new File("../dashboard-0.0.12/oel");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath()
                        + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));

                stream.write(bytes);
                stream.close();



                return "You successfully uploaded file=" + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name
                    + " because the file was empty.";
        }
    }

我面临以下错误:-

加载资源失败:服务器响应状态为 500 (HTTP/1.1 500)

可能未处理的拒绝: {“数据”:{“时间戳”:1510643953084,“状态”:500,“错误”:“内部 服务器 错误","异常":"java.lang.NullPointerException","消息":"否 信息 可用","path":"/api/oel/csv"},"status":500,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null ],"jsonpCallbackParam":"callback","url":"/api/oel/csv","data":{},"headers":{"Accept":"application/json, 文本/纯文本, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"HTTP/1.1 500"}

有人可以帮忙吗?

谢谢

【问题讨论】:

  • 你试过调试了吗?

标签: java html angularjs spring-mvc spring-boot


【解决方案1】:

我会推荐这个:Apache Commons FileUpload

if (ServletFileUpload.isMultipartContent(request)) {
    FileItemFactory factoryItem = new DiskFileItemFactory();
    ServletFileUpload uploadFile = new ServletFileUpload(factoryItem);

    try {
        List items = uploadFile.parseRequest(request);
        Iterator iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem item = (FileItem) iterator.next();

            if (!item.isFormField()) {
                String fileName = item.getName();

                String root = getServletContext().getRealPath("/");
                File path = new File(root + "/uploads");
                if (!path.exists()) {
                    boolean status = path.mkdirs();
                }

                File uploadedFile = new File(path + "/" + fileName);
                System.out.println(uploadedFile.getAbsolutePath());
                item.write(uploadedFile);
            }
        }
    } catch (FileUploadException ex) {
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多