【问题标题】:React file upload with FormData使用 FormData 响应文件上传
【发布时间】:2019-01-25 04:23:35
【问题描述】:

尝试使用 FormData 上传文件。文件成功上传到服务器并出现在上传文件夹中,但服务器发回“错误请求”。在服务器上

"message": "\"file\" is required"

似乎 multer 没有将文件解析为正文,因此 req.body.file 不存在。 Angular 中的类似代码用作时钟。区别在哪里?

反应:

onSubmit(e) {
    e.preventDefault();
    let body = new FormData();

    let data = Array.prototype.filter.call(e.target.elements, 
      (input) => {
        if (input.nodeName === 'BUTTON') return false;
        return true;
      });
    Array.prototype.map.call(data, (input) => {
      input.id !== 'file' ? body.append( input.id, input.value )
      : body.append('file', input.files[0]);
      
    });
    fetch('http://localhost:4040/api/books/create', {
      method: 'POST',
      headers: { 
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
     },
     body: body,
    }).then(res => res.json())
      .then(response => {
        console.log(response);
      })
      .catch(error => console.error('Error:', error));
  }

  render() {
    return (
      <form onSubmit={this.onSubmit} encType="multipart/form-data" className="form-add">
        <input type="file" id="file" accept=".jpg, .png" required />
        <input type="text" id="author" placeholder="author" required />
        <input type="text" id="title" placeholder="Title" required />
        <textarea id="description" rows="10" placeholder="Description..." required ></textarea>
        <input type="number" id="rating" placeholder="Number from 1 to 5" min="1" max="5" required/>
        <select name="status" id="status">
          <option value="true">true</option>
          <option value="false">false</option>
        </select>
        <button type="submit">Submit</button>
      </form>
    );
  }

角度:

@ViewChild("fileInput") fileInput;
  // Loading file
  addFile(): any {
    let fi = this.fileInput.nativeElement;
    if (fi.files && fi.files[0]) {
        return fi.files[0];
    }
    return null;
  }

  onSubmit(value: string) {
    let body = new FormData();
    body.append("file",this.addFile());
    Object.keys(this.form.value).forEach(k => {
      body.append(k, this.form.value[k]);
    });
    let httpOptions = {
      headers: new HttpHeaders({ 'Authorization': 'Bearer ' + localStorage.getItem('jwtToken') })
    };
    this.http.post('http://localhost:4040/api/books/create', body, httpOptions).subscribe(
      data => {
        console.log(data);
        alert('Success!');
      }
    );
  }

【问题讨论】:

标签: reactjs multipartform-data multer


【解决方案1】:

问题出在服务器端的验证参数中。现在看起来像file: Joi.any()

【讨论】:

    猜你喜欢
    • 2017-08-30
    • 2014-06-08
    • 2016-03-09
    • 2012-10-10
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多