使用Angular 2和Spring上传文件

使用Angular 2和Spring上传文件,spring,angular,file-upload,Spring,Angular,File Upload,有没有一种简单的方法可以使用Angular客户端和Spring服务器上传文件?在找到最简单的工作解决方案之前,我必须搜索不同的问题/答案,使用Angular而不使用外部库。 在解决方案下方,我找到了几个关于StackOverflow的答案,使用StackOverflow问答风格,希望能有所帮助。我找到的解决方案。一旦我再次找到我获取代码的答案,我将引用它们 file-upload.component.html <input type="file" (cha

有没有一种简单的方法可以使用Angular客户端和Spring服务器上传文件?在找到最简单的工作解决方案之前,我必须搜索不同的问题/答案,使用Angular而不使用外部库。
在解决方案下方,我找到了几个关于StackOverflow的答案,使用StackOverflow问答风格,希望能有所帮助。

我找到的解决方案。一旦我再次找到我获取代码的答案,我将引用它们

file-upload.component.html

    <input type="file" 
           (change)="fileChange($event)"
           placeholder="Upload file" 
           accept=".pdf,.doc,.docx">
弹簧控制器:

    package unisvid.sessionManager.server.controller;

    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Iterator;

    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;

    @CrossOrigin(origins = "*")
    @RestController
    public class FileUploadController {

      @RequestMapping(value = "/upload", method = RequestMethod.POST)
      public void UploadFile(MultipartHttpServletRequest request) throws IOException {

        Iterator<String> itr = request.getFileNames();
        MultipartFile file = request.getFile(itr.next());
        String fileName = file.getOriginalFilename();
        File dir = new File("/Users/luigi/Documents/tmp/");
        if (dir.isDirectory()) {
          File serverFile = new File(dir, fileName);
          BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
          stream.write(file.getBytes());
          stream.close();
        }
      }
    }
包unisvid.sessionManager.server.controller;
导入java.io.BufferedOutputStream;
导入java.io.File;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.util.Iterator;
导入org.springframework.web.bind.annotation.CrossOrigin;
导入org.springframework.web.bind.annotation.RequestMapping;
导入org.springframework.web.bind.annotation.RequestMethod;
导入org.springframework.web.bind.annotation.RestController;
导入org.springframework.web.multipart.MultipartFile;
导入org.springframework.web.multipart.multipartttpServletRequest;
@交叉原点(原点=“*”)
@RestController
公共类FileUploadController{
@RequestMapping(value=“/upload”,method=RequestMethod.POST)
public void UploadFile(multipartttpServletRequest请求)引发IOException{
迭代器itr=request.getFileNames();
MultipartFile file=request.getFile(itr.next());
字符串文件名=file.getOriginalFilename();
File dir=新文件(“/Users/luigi/Documents/tmp/”);
if(dir.isDirectory()){
文件服务器文件=新文件(目录,文件名);
BufferedOutputStream=新的BufferedOutputStream(新文件输出流(服务器文件));
stream.write(file.getBytes());
stream.close();
}
}
}

Angular 2+为上传文件提供了良好的支持

以下是我的解决方案:

内容类型保留为空非常重要。如果将“内容类型”设置为“多部分/表单数据”,则上载将不起作用

upload.component.html

<input type="file" (change)="fileChange($event)" name="file" />
<input type="file" (change)="fileChange($event)" name="file" />
export class UploadComponent implements OnInit {
    constructor(public http: Http) {}

    fileChange(event): void {
        const fileList: FileList = event.target.files;
        if (fileList.length > 0) {
            const file = fileList[0];

            const formData = new FormData();
            formData.append('file', file, file.name);

            const headers = new Headers();
            // It is very important to leave the Content-Type empty
            // do not use headers.append('Content-Type', 'multipart/form-data');
            headers.append('Authorization', 'Bearer ' + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9....');
            const options = new RequestOptions({headers: headers});

            this.http.post('https://api.mysite.com/uploadfile', formData, options)
                 .map(res => res.json())
                 .catch(error => Observable.throw(error))
                 .subscribe(
                     data => console.log('success'),
                     error => console.log(error)
                 );
        }
    }
}