使用FormData反应文件上传

时间:2018-08-18 09:06:52

标签: reactjs multipartform-data multer

尝试使用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!');
      }
    );
  }

1 个答案:

答案 0 :(得分:0)

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