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

时间:2016-09-23 15:02:57

标签: javascript node.js express reactjs axios

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

我正在使用的axios代码(我在前端使用了反应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')
  }); 

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

6 个答案:

答案 0 :(得分:14)

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

import FormData from 'form-data'

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

npm install --save form-data

一旦我完成了所有这些,这就是我在行动中使用它的方式:

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
  });
};}

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

  1. 在数据对象传递到axios.post调用之后,我将一些头文件作为配置对象包含在内。您在此处包含的内容类型是关键。您正在提交多部分/表单数据内容类型。
  2. 在该Content类型标题中,我还添加了一个边界,该边界是从您之前创建的数据对象派生的。
  3. 此处使用的'文件'只是我传递给我的操作的文件对象。它只是我用于对象的名称,你可以在这里使用你想要的任何东西。
  4. 希望这会有所帮助,这解决了我尝试将图像提交到后端的所有问题(在我的情况下是一个休息服务 - 通过邮件调用)。

答案 1 :(得分:11)

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

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

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

答案 2 :(得分:3)

以下是我实施它的方式:

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

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

以下是我在端点上的结果:

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 
    }, ...
}

答案 3 :(得分:1)

我想说的是,不要手动执行此操作,您可以使用名为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>
          );
  }
}

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

答案 4 :(得分:0)

使用HTML5,您可以使用FormData() 构造一组代表要发送的表单字段及其值的键/值对。在大多数情况下,就像在提交表单的用户中一样,使用的方法是FormData.set(),可以是以下两种形式的manipulated

  

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

     

formData.set(名称,值);

     

formData.set(名称,值,文件名);

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

以下是我所说的摘要:

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 
      })
  })

答案 5 :(得分:0)

向后端上传图片所需的只是标题 multipart/form-data、图片详细信息(urinametype)和表单数据。

import FormData from 'form-data'

const config = {
   headers: {

    'Content-Type': 'multipart/form-data'

   }
}


const data = new FormData();

data.append('image', {
    uri: image.uri,
    name: image.uri.split('/').pop(), //split the uri at / and get the last element of the resulting array which actually is the name with the image extention (e.g, abc.jpg)
   type: image.type // type needs to be modified. keep reading
})

现在是重要的一点。很多时候图像详细信息中的类型不是完整类型(例如,它只返回“图像”但实际类型是“图像/jpeg”),这会导致 network error

现在为了获得准确的类型,我们可以使用一些第三方包来做到这一点。

例如,我们可以使用 mime

import mime from 'mime'

type: mime.getType(image.uri)

最后,我们只需要发送请求即可。

axios.post('url', data, config)
.then(...)
.catch(...)

不仅是图片,我们还可以使用完全相同的程序上传视频。