gpt4 book ai didi

javascript - 如何使用任何 Node 库尤其是 axios 将文件上传到服务器?

转载 作者:行者123 更新时间:2023-11-30 14:31:03 24 4
gpt4 key购买 nike

我正在使用 CURL 命令将文件上传到服务器,但在少数 CLI 中会出现问题。当我运行我的 Node 应用程序时,只有安装了 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.'});
});

最佳答案

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

您需要使用 post 请求将文件发送到服务器,然后根据请求的成功使用 promises 进行捕获或解析。

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 文档

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

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

关于javascript - 如何使用任何 Node 库尤其是 axios 将文件上传到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51159522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com