簡體   English   中英

使用從本地讀取的 jQuery 上傳文件

[英]Upload file using jQuery reading from local

我正在嘗試在純 js 中使用 jQuery 上傳文件,從本地路徑讀取文件

規范的方法是從附加到 FormData 的 html 輸入中獲取文件

var form = new FormData();
form.append("test", " [69]");
form.append("file", fileInput.files[0], "/C:/test.txt");

var settings = {
  "url": "https://...",
  "method": "POST",
  "timeout": 0,
  "processData": false,
  "mimeType": "multipart/form-data",
  "contentType": false,
  "data": form
};

但是我需要在不使用 html 界面的情況下按需讀取文件。 如何讀取此文件並將其放入維護/獲取 MIME 類型的 blob 中? 我已經嘗試過這個成功:

const fd = fs.openSync(path, 'r');
const stat = fs.statSync(path);
const bytecount = stat.size;
const buf = Buffer.alloc(bytecount)
fs.readSync(fd, buf, 0, bytecount, 0);
const  file = new Blob([buf]);
// I have to get the real MIME type
//const file2 = file.slice(0, file.size, "text/plain")
formData.append('file', file2, 'blob');

謝謝

您可以使用 javascript FileReader 執行此操作

const htmlFileElem = document.querySelector('whatever')
htmlFileElem.onChange = function(e) {
const reader = new FileReader()
reader.onload = function(e) {
console.log(e)
// get the file blob format
const file_blob = e.target.result
}
reader.readAsDataURL(e.target.files[0]) // note for a single file
// to get the mime type do this
const mime_type = e.target.files[0].type
}

我希望這是你正在尋找的,它也有幫助

或者這樣做

fetch(url_to_remote_file)
.then(res => res.blob())
.then(blob => {
 console.log(blob) // you will see things you need here
})

暫無
暫無

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

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