[英]Send file with form-data and axios
I am trying to send a video to a videosite, I am able to upload the video using the REST api and postman, so I know the api works as intended. 現在我想使用 axios 做同樣的請求。 我的代碼類似於如何使用表單數據和 axios 的示例:
const form = new FormData();
const stream = fs.createReadStream(PATH_TO_FILE);
form.append('image', stream);
// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
const formHeaders = form.getHeaders();
axios.post('http://example.com', form, {
headers: {
...formHeaders,
},
})
.then(response => response)
.catch(error => error)
我收到錯誤data: 'Content-Length is required'
有任何想法嗎?
可能是我把你的問題弄錯了,你想在 header 中添加 Content-Length。 我可以看到您正在上傳視頻 stream。 所以首先你必須計算數據塊的長度。
('Content-Length', File.getSize(stream)) 參考: 我可以在沒有內容長度 header 的情況下將文件上傳到 S3 嗎?
您可以將發布請求設為多部分類型:“Content-Type”:“multipart/form-data”。 將大數據發送到服務器的首選方式。 您可以查看此鏈接: How do I set multipart in axios with react?
如果我的問題有誤,請評論或回復。 謝謝
我的問題的解決方案是相應地設置 Content-Length :
"Content-Length": fs.statSync(filePath)['size']
我認為處理這個問題的最好方法是實際使用 FormData 自己的方法:
const headers = { 'content-length': formData.getLengthSync(), ...formData.getHeaders() }
這將更准確,因為它包含您可能添加的任何其他數據。
說明一下,如果您使用的是 ReadStream,則必須改用異步 function。
const { promisify } = require('util')
const getLength = promisify(formData.getLength.bind(formData))
const contentLength = await getLength()
const headers = { 'content-length': contentLength, ...formData.getHeaders() }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.