【问题标题】:How to upload picture in Spring and Angular2如何在Spring和Angular2中上传图片
【发布时间】:2017-06-23 12:30:43
【问题描述】:

我想在我的应用中上传图片这是我的 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);
  }

我得到这个错误

ERROR {"timestamp":1498220487868,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"必填请求部分“文件”不存在","path":"/webapp/api/picture/upload"}

【问题讨论】:

标签: spring angular file upload multipart


【解决方案1】:

您指定 @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

【讨论】:

  • 我也看到上传了多个文件,所以你应该把参数改成一个数组:@RequestPart("uploads") MultipartFile[] uploads
  • @ledniov 啊,你是对的,我会更新答案。
  • 如何上传一个文件而不是多个文件?因为我又出错了
  • @CrazyDeveloper 删除MultipartFile 上的方括号和uploads 键,只在formData 上附加一个文件。
  • 但我得到了同样的错误,ERROR {"timestamp":1498229320921,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart .support.MissingServletRequestPartException","message":"所需的请求部分'上传'不存在","path":"/webapp/api/picture/upload"}
猜你喜欢
  • 2022-01-10
  • 2014-12-04
  • 2017-01-01
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 2013-06-23
相关资源
最近更新 更多