尝试将CS​​V文件上传到服务器时出现空指针异常

时间:2017-11-14 07:56:19

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

我正在尝试将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“, ”消息“:” 无   信息   可用的”, “路径”: “/ API / OEL / CSV”}, “状态”:500, “配置”:{ “方法”: “POST”, “transformRequest”:[空], “transformResponse”:[空], “jsonpCallbackParam”: “回调”, “URL”: “/ API / OEL / CSV”, “数据”:{}, “报头”:{ “接受”:“应用/ JSON,   text / plain的,    / “ ”内容类型“: ”应用/ JSON;字符集= UTF-8“}}, ”状态文本“:” HTTP / 1.1   500" }

有人可以帮忙吗?

由于

1 个答案:

答案 0 :(得分:-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();
    }
}