如何使用任何节点库(尤其是axios)将文件上传到服务器?

时间:2018-07-03 16:48:51

标签: javascript node.js express axios

我正在使用CURL命令将文件上传到在少数几个CLI中引起问题的服务器。 当我运行节点应用程序时,只有安装了CURL的CLI才能正常运行。

let mnmPath = `http://xyz/api/123456/mnm-api`;
exec(`curl -X PUT -H "x-cdn-path:" ${mnmPath } --upload-file abcd.txt`, (error, stdout) => {
    if (error) {
      console.log({status: 1, message: 'Error while uploading Tarball to CDN'});
    }
    console.log({status: 0, message: 'CDN upload completed.'});
  });

1 个答案:

答案 0 :(得分:2)

您需要以某种方式获取文件,在我的示例中,我假设您有一个文件选择器,您可以从中访问数据

您将希望使用发布请求将文件发送到服务器,然后根据请求的成功使用promise进行捕获或解决。

  

https://github.com/axios/axios

     

https://developer.mozilla.org/en-US/docs/Web/API/FormData

     

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

/*
   example of getting a file from DOM but as long as you
   pass a file to the function should be good 
*/


// es6 promise
function postFileToServer(file) {
  const formData = new FormData();
  formData.append("file", file);

  axios.post('/your-endpoint', formData)
    .then(res => /* do something with res*/ console.log(res))
    .catch(e => console.log('upload failed'))
}

function submit() {
  const file = document.getElementById("file").files;
  if (file.length > 0) {
    postFileToServer(file[0])
  }
}
input {display: block}
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<input id="file" type="file" />
<button onclick="submit()">submit</button>

来自FormData文档

  

FormData接口提供了一种轻松构造代表表单字段及其值的键/值对集合的方法,然后可以使用XMLHttpRequest.send()方法轻松发送该键/值对。如果编码类型设置为“ multipart / form-data”,则使用与表单相同的格式。

基本上,它将其格式化为易于操作的对象,准备发送给外部服务。您将需要检查您所使用的服务如何接受该文件。