Javascript 你如何使用Axios将图像发送到节点js?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39663961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:47:23  来源:igfitidea点击:

How do you send images to node js with Axios?

javascriptnode.jsexpressreactjsaxios

提问by J. Bones

Is there a way to send an array of images (or a single image) to node using axios?

有没有办法使用 axios 将一组图像(或单个图像)发送到节点?

The axios code I'm using(I'm using react js on the front end):

我正在使用的 axios 代码(我在前端使用 react js):

onFormSubmit(event){
    event.preventDefault();
    let payload = this.state;
    console.log("in onFormSubmit!!! with state: ", this.state, "and payload: ", payload);
    axios.post('/api/art', payload)
    .then(function(response){
    console.log('saved successfully')
  }); 

The research I've done suggests that perhaps there isn't a supported way to send image files to node using axios, but this seems strange to me. Is there a way?

我所做的研究表明,也许没有一种受支持的方式使用 axios 将图像文件发送到节点,但这对我来说似乎很奇怪。有办法吗?

回答by Cmontalvo80

Here is the way I got this to work properly. I had to make use of an object called FormData. I used the import:

这是我让它正常工作的方式。我不得不使用一个叫做 FormData 的对象。我使用了导入:

import FormData from 'form-data'

Of course before this import I had to run the npm install for it:

当然,在此导入之前,我必须为它运行 npm install:

npm install --save form-data

Once I did all that, here is how I used it within my action:

完成所有这些后,以下是我在行动中使用它的方式:

let data = new FormData();
data.append('file', file, file.fileName);

return (dispatch) => {
axios.post(URL, data, {
  headers: {
    'accept': 'application/json',
    'Accept-Language': 'en-US,en;q=0.8',
    'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
  }
})
  .then((response) => {
    //handle success
  }).catch((error) => {
    //handle error
  });
};}

The important pieces to note here are:

这里需要注意的重要部分是:

  1. I included some headers as a configuration object after the data object passed into the axios.post call. The content type you're including here is the key. You're submitting a multipart/form-data content type.
  2. Within that Content type header, I also added a boundary, which is derived from the data object you created earlier.
  3. The 'file' used here is just the file object I passed into my action. It's just the name I used for my object, you can use anything you want here.
  1. 在将数据对象传递到 axios.post 调用之后,我包含了一些标题作为配置对象。您在此处包含的内容类型是关键。您正在提交多部分/表单数据内容类型。
  2. 在那个 Content 类型标题中,我还添加了一个边界,它派生自您之前创建的数据对象。
  3. 这里使用的“文件”只是我传递给我的动作的文件对象。这只是我用于对象的名称,您可以在这里使用任何您想要的名称。

Hope this helps, this cleared up all of the issues I had with trying to submit an image to a backend (in my case a rest service - through a post call).

希望这会有所帮助,这解决了我尝试向后端提交图像时遇到的所有问题(在我的情况下是休息服务 - 通过电话后)。

回答by Yangshun Tay

Yes you will have to set the content type in your axios request:

是的,您必须在 axios 请求中设置内容类型:

axios.put(url, imageFile, {
  headers: {
    'Content-Type': imageFile.type
  }
});

where imageFileis an HTML5 file (https://developer.mozilla.org/en/docs/Web/API/File) which should be an image in your case.

哪里imageFile是 HTML5 文件(https://developer.mozilla.org/en/docs/Web/API/File),在您的情况下应该是图像。

回答by Volodymyr Synytskyi

Here is how I implemented it:

这是我如何实施它:

onFormSubmit(event){
    var form = new FormData();
    files.forEach(file => {
        form.append(file.name, file);
    });
    form.append('foo', 'bar');
    axios.post('/api/art', form)    
}); 

On node js server make sure to use some middle-ware which handles multipart requests. I used multer.

在节点 js 服务器上确保使用一些处理多部分请求的中间件。我使用了multer

Here are my results on the endpoint:

这是我在端点上的结果:

req.body - { foo: 'bar' }
req.files - { 
    'r1.jpg': { 
      fieldname: 'r1.jpg',
      originalname: 'r1.jpg',
      name: 'e2f4b9874fd7d6115b9f7440b9ead3a0.jpg',
      encoding: '7bit',
      mimetype: 'image/jpeg',
      path: '/tmp/e2f4b9874fd7d6115b9f7440b9ead3a0.jpg',
      extension: 'jpg',
      size: 45641,
      truncated: false,
      buffer: null 
    }, ...
}

回答by Billal Begueradj

With HTML5 you can use FormData()to construct a set of key/value pairs representing form fields and their valuesyou want to send. In most cases, as in a user submitting a form, the method to use is FormData.set()which can be manipulatedin its 2 forms:

使用 HTML5,您可以使用构建一组键/值对来表示要发送的表单字段及其值。在大多数情况下,如在用户提交一个表单,该方法在使用时可被操作在其2种形式:FormData()FormData.set()

There are two versions of this method: a two and a three parameter version:

formData.set(name, value);

formData.set(name, value, filename);

此方法有两个版本:两个和三个参数版本:

formData.set(name, value);

formData.set(name, value, filename);

Once you construct your data object, do not forget to specify the multipart content type header for your HTTP POST request so that you can send the file to your server.

构建数据对象后,不要忘记为 HTTP POST 请求指定多部分内容类型标头,以便可以将文件发送到服务器。

Below is a summary of what I said:

以下是我所说的摘要:

onFormSubmit(event){
    let formData = new FormData(); // instantiate it
    // suppose you have your file ready
    formData.set('file', yourFile);
    // add some data you collected from the input fields
    formData.set('data1', dataInputField1); // suppose you got dataInputField1 from your HTML5 form input
    axios.post('/api/art', formData, {
      headers: {
       'content-type': 'multipart/form-data' // do not forget this 
      }})
  }

回答by Harkirat Saluja

I would say instead of doing this manually you can use a library called react-dropzonefor this . So basically what you need to do is :-

我想说,您可以为此使用一个名为react-dropzone的库,而不是手动执行此操作。所以基本上你需要做的是:-

import React,{Component} from 'react';
import Dropzone from 'react-dropzone';
import request from 'superagent';

class DropZone extends Component{

  onDrop(files){
    var file = new FormData();
    file.append('name',files[0])
    var req=request
              .post('http://localhost:8000/api/v0/image/')
              .send(file);
    req.end(function(err,response){
        console.log("upload done!!!!!");
    });
  }

  render(){
    return(
      <div>
        <Dropzone onDrop={this.onDrop}>
          <div>Try dropping some files here, or click to select files to upload.</div>
        </Dropzone>
      </div>
          );
  }
}

You can check herefor git repo. I have implemented this in django but i dont think backend should be a problem, you can use node

你可以在这里查看 git repo。我已经在 django 中实现了这个,但我不认为后端应该是一个问题,你可以使用 node