如何在Spring和Angular2上传图片

时间:2017-06-23 12:30:43

标签: spring angular file upload multipart

我想在我的应用中上传图片,这是我的Angular 2代码

  constructor () {
                    this.progress = Observable.create(observer => {
                          this.progressObserver = observer
                             }).share();
                                }

public makeFileRequest (url: string, params: string[], files: File[]): 
 Observable<any> {
    return Observable.create(observer => {
        let formData: FormData = new FormData(),
            xhr: XMLHttpRequest = new XMLHttpRequest();

        for (let i = 0; i < files.length; i++) {
            formData.append("uploads[]", files[i], files[i].name);
        }

        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    observer.next(JSON.parse(xhr.response));
                    observer.complete();
                } else {
                    observer.error(xhr.response);
                }
            }
        };

        xhr.upload.onprogress = (event) => {
            this.progress = Math.round(event.loaded / event.total * 100);

            this.progressObserver.next(this.progress);
        };

        xhr.open('POST', url, true);
        xhr.send(formData);
    });
}

这是我的弹簧控制器

@RequestMapping(value = "/upload", method = RequestMethod.POST)
 @ResponseBody
 public ResponseEntity<?> uploadFile(
       @RequestParam("file") MultipartFile uploadfile) {

   try {
       // Get the filename and build the local file path (be sure that the
       // application have write permissions on such directory)
       String filename = uploadfile.getOriginalFilename();
       String directory = "/assets/images";
       String filepath = Paths.get(directory, filename).toString();

       // Save the file locally
       BufferedOutputStream stream =
               new BufferedOutputStream(new FileOutputStream(new File(filepath)));
       stream.write(uploadfile.getBytes());
       stream.close();
   }
   catch (Exception e) {
       System.out.println(e.getMessage());
       return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
   }

   return new ResponseEntity<>(HttpStatus.OK);
  }

我收到此错误

错误{“timestamp”:1498220487868,“status”:400,“error”:“错误请求”,“异常”:“org.springframework.web.multipart.support.MissingServletRequestPartException”,“message”:“必需请求部分'文件'不存在“,”路径“:”/ webapp / api / picture / upload“}

1 个答案:

答案 0 :(得分:0)

您指定@RequestParam("file"),这意味着Spring会使用键file等待参数,但您使用键uploads附加数据。

另外,正如@ledniov所述,您正在接收一系列多部分文件,而不仅仅是一部分。

如果您想使用密钥file

,请进行更正
// Front-End: change "uploads" to "file"
formData.append("file[]", files[i], files[i].name);
// Back-End: takes a MultipartFile array
@RequestParam("file") MultipartFile[] uploadfile

如果您想使用密钥uploads

,请进行更正
// Back-End: change "file" to "uploads" and takes a MultipartFile array
@RequestParam("uploads") MultipartFile[] uploadfile