angular4应用程序中的FormData上传

FormData upload in angular4 application

在我的 angular4 应用程序中,我正在尝试将视频上传到服务器。 但无论我向内容类型添加什么,它总是会导致服务器出错。 在 angular 1 中使用 { 'Content-Type': undefined }

命中相同的 api

我在 angular 中尝试了同样的方法,但它没有用。 数据和一切都是正确的。 我试过将内容类型设置如下

headers.append('Content-Type', 'multipart/form-data');
headers.append('Authorization', token);
headers.set('Accept', 'application/json');

还有如下

headers.append('Content-Type', 未定义);

以下为http请求方式:

public uploadVideo(formData: any) {


        var Upload = this.baseUrl + this.ngAuth.getApiUrl('Upload');
        var authData = JSON.parse(this.localStorage.localStorageGet('token'));
        var token = 'Bearer ' + authData.token;
        var self = this;

        var headers = new Headers();
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Authorization', token);
        headers.set('Accept', 'application/json');

        return this.http.post(Upload , formData, { headers: headers, method: 'POST' })
            .map((res: Response) => res.json());

    }

请指导! 谢谢

所以在经历了很多解决方案之后,我偶然发现了这个 issue

它说不要将 Content-Type 添加到 header。 所以根据我的要求 header 我删除了

headers.append('Content-Type', 'multipart/form-data');

谢谢!

我会用Angular6和SpringBoot来做参考

Angular 6 :

onSubmit(){
const formdata: FormData = new FormData();
console.log(this.currentFileUpload)
formdata.append('uploadedFile', this.currentFileUpload);
formdata.append('description',"My Desc");
formdata.append('companyName',"ABC")
formdata.append('numberOfRecords',"2")
console.log(formdata.get('uploadedFile'))

this.asyncService.makeUploadRequest('file/upload',formdata).subscribe(response => {
  console.log(response)
  if(response.responseCode == '00'){
    console.log('Successfully uploaded')
  }
  else {
    console.log("error")
  }
 });
}


makeUploadRequest(method, body) : Observable<any> {
    const url = "http://localhost:8097" + "/" + method;

    const headers = new Headers();
    this.token="Bearer"+" "+localStorage.getItem('token'); 
    headers.append('Authorization', this.token);
    // No need to set 'content type'
    const options = new RequestOptions({headers: headers});
    return this.http.post(url, body, options).pipe(
        map((response : Response) => {
            var json = response.json();                
         return json; 
        })
    );
}

Spring 启动 API :

@RestController
@RequestMapping(value = { "/file" })
public class FileController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Response uploadFile(@RequestParam("uploadedFile") MultipartFile uploadedFileRef){
        System.out.println(uploadedFileRef);
    }
}