簡體   English   中英

如何使用任何節點庫(尤其是axios)將文件上傳到服務器?

[英]How to upload a file to server using any node library especially 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.'});
  });

您需要以某種方式獲取文件,在我的示例中,我假設您有一個文件選擇器,並且您可以從中訪問數據

您將要使用發布請求將文件發送到服務器,然后根據請求的成功使用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”,則它使用與表單相同的格式。

基本上,它將其格式化為易於操作的對象,准備發送給外部服務。 您將需要檢查您所使用的服務如何接受該文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM