简体   繁体   English

如何在Spring和Angular2中上传图片

[英]How to upload picture in Spring and Angular2

I want to upload picture in my app this is my Angular 2 code 我想在我的应用程序中上传图片,这是我的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);
    });
}

And this is my spring controller 这是我的弹簧控制器

@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);
  }

And I get this error 我得到这个错误

ERROR {"timestamp":1498220487868,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/webapp/api/picture/upload"} 错误{“时间戳”:1498220487868,“状态”:400,“错误”:“错误的请求”,“异常”:“ org.springframework.web.multipart.support.MissingServletRequestPartException”,“消息”:“所需的请求部分'文件“不存在”,“路径”:“ / webapp / api /图片/上传”}

You specify @RequestParam("file") , which means Spring waits for an argument with the key file , but you append your data with the key uploads . 您指定@RequestParam("file") ,这意味着Spring等待带有密钥file的参数,但是您将数据附加了密钥uploads

Also, as said by @ledniov , your are receiving an array of multipart files, not only one. 另外,正如@ledniov所说 ,您正在接收一组多部分文件,而不仅仅是一个。

Corrections if you want to use the key file : 如果要使用密钥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

Corrections if you want to use the key uploads : 如果要使用密钥uploads请进行更正:

// Back-End: change "file" to "uploads" and takes a MultipartFile array
@RequestParam("uploads") MultipartFile[] uploadfile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM