[我正在尝试使用访存API和formData-有角度的材料上传文件

问题描述 投票:0回答:1

我正在尝试上传图像并将formData发送到后端。

我正在使用formData.append附加上载的文件和fetchAPI来发送formData。

我的输入如下所示

<input style="display:none" type="file"
                               (change)="fileChange($event)"
                               #fileInput>
fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      let file: File = fileList[0];
      let formData: FormData = new FormData();
    formData.append('uploadFile', file, file.name);
    console.log('formData', formData);
    this.handleUpload(formData);
    }
  }
handleUpload(formData) {
    const url = `/upload?`;
    let result;
    const req = new Request(proxyurl + url,
      {
        method: 'POST',
        headers: {
          'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
    },
        body: formData
      });
    fetch(req)
      .then(response => response.text())
      .then(() => {
        if (result.data) {
          console.log('response ', result.data);
        } else {
          console.log('request failed');
        }
      })
      .catch(() => console.log('Can\'t access ' + url + ' response. Blocked by browser?'));
  }

[当我启动该服务时,我得到状态码:422无法处理的实体,响应如下

{"error":{"message":"?exception.illegalargument?"}}

请求有效载荷如下

------WebKitFormBoundary8E02ll3T0mo433bu
Content-Disposition: form-data; name="uploadFile"; filename="Screen Shot 2019-10-04 at 10.49.34 AM.png"
Content-Type: image/png


------WebKitFormBoundary8E02ll3T0mo433bu--

[请帮助我了解如何使它正常工作。

javascript angular-material fetch multipartform-data form-data
1个回答
0
投票
我通过执行以下操作使其工作:

删除了标头,并检查服务器是否期望uploadFile。

下面的工作代码:

fileChange(event) { let fileList: FileList = event.target.files; if (fileList.length > 0) { let file: File = fileList[0]; let formData: FormData = new FormData(); formData.append('uploadedFile', file, file.name); this.handleUpload(formData); } } handleUpload(formData) { const url = `/upload?`; let result; const req = new Request(url, { method: 'POST', headers: {}, body: formData }); fetch(req) .then(response => response.text()) .then(() => { if (result.data) { console.log('response data ', result.data); } else { console.log('request failed'); } }) .catch(() => console.log('Can\'t access ' + url + ' response. Blocked by browser?')); }

© www.soinside.com 2019 - 2024. All rights reserved.