如何在Spring上传中解决MissingServletRequestPartException

时间:2017-03-27 07:40:49

标签: java spring spring-mvc spring-boot upload

我在Spring上传图片时遇到问题。我遇到了无数问题,我试图解决这些问题。对于我目前的错误,我已经尝试了春天提供的所有解决方案,但它仍然存在。根据spring,可以通过包含MultipartResolver。http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/support/MissingServletRequestPartException.html来解决MissingServletRequestPartException问题。我已经这样做了(见下文),但问题仍然存在。

错误

timestamp: 1490599131962, status: 400, error: "Bad Request",…}
error:"Bad Request"
exception:"org.springframework.web.multipart.support.MissingServletRequestPartException"
message:"Required request part 'uploadfile' is not present"
path:"/uploadFile"

配置

 @Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(100000);
        return new CommonsMultipartResolver();
    }

控制器

 public ResponseEntity<?> uploadFile(@RequestParam("uploadfile") MultipartFile uploadfile, Picture picture, Principal principal, MultipartHttpServletRequest request) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        picture.setUser(user);
        Iterator<String> itrator = request.getFileNames();
        MultipartFile multiFile = request.getFile(itrator.next());
        try {
            System.out.println("File Length:" + multiFile.getBytes().length);
            System.out.println("File Type:" + multiFile.getContentType());
            // Crop the image (uploadfile is an object of type MultipartFile)
            BufferedImage croppedImage = cropImageSquare(multiFile.getBytes());
            String fileName=multiFile.getOriginalFilename();
            System.out.println("File Name:" +fileName);
            String path=request.getServletContext().getRealPath("/");

            // Get the filename and build the local file path
            File directory=    new File(path+ "/uploads");
            directory.mkdirs();
            String filename = uploadfile.getOriginalFilename();
            String ext = FilenameUtils.getExtension(filename);
            File outPutFile = new File(directory.getAbsolutePath()+System.getProperty("file.separator")+picture.getUploadfile());
            ImageIO.write(croppedImage, ext, outPutFile);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        pictureService.save(picture, uploadfile);
        return new ResponseEntity<>(HttpStatus.ACCEPTED);
    } 

JS FILE

'use strict';
var $formUploader = $("#upload-file-input");
  $formUploader.on("submit", function(e){
   e.preventDefault();
   var data = new FormData(this);
   $.each($formUploader.serializeArray(), function(i, field) {
           data[field.name] = field.value;
       });*/

   $.ajax({
           //dataType: 'json',
           url: $formUploader.prop('action'),
           type: "POST",
           //data: new FormData($("#upload-file-input")[0]),
           data: data,
           enctype: 'multipart/form-data',
           processData: false,
           contentType: false,
           cache: false,
           success: function (data) {
           console.log(data);
             // Handle upload success
             $("#upload-file-message").text("File succesfully uploaded");
           },
           error: function (response) {
             console.log(response);
             // Handle upload error
             $("#upload-file-message").text("File not uploaded (File might be big, size needed.)");
           }
         });
});

表格

<form  id="upload-file-input" th:action="@{/uploadFile}" method="post" th:object="${picture}"
          enctype="multipart/form-data" class="form-inline inline new-item">
        <div th:replace="common/layout :: flash"></div>
        <fieldset>
            <legend> Upload Picture</legend>
            <div class="row">
                <div class="col s12 l8">
                    <div class="file-wrapper">
                        <input type="file" id="file" name="uploadfile" />
                        <span class="placeholder" data-placeholder="Choose an image...">Choose an image...</span>
                        <label for="file" class="button">Browse</label>
                        <span id="upload-file-message"></span>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">Upload</button>
            </div>
        </fieldset>
        <div class="style16"></div>
    </form>

1 个答案:

答案 0 :(得分:0)

您已将所有表单值添加到FormData,但未添加文件内容。这是如何做到的:

...

var data = new FormData(this);
$.each($formUploader.serializeArray(), function(i, field) {
       data[field.name] = field.value;
});    
//next line will add content of file
data.append('fileContent', $('#file').files[0]);

$.ajax({ ...

您可以使用任何名称而不是fileContent,但这并不重要。

如果用户允许一次选择多个文件,则必须添加所有这些文件的内容:

...

var data = new FormData(this);
$.each($formUploader.serializeArray(), function(i, field) {
       data[field.name] = field.value;
});    

$.each($('#file').files, function(i, file) {
    formData.append('fileContent' + i, file);
});

$.ajax({ ...