4 回答

TA贡献1876条经验 获得超6个赞
您不应该在控制台中看到 FormData 对象的内容,因为它不可序列化。您可以改为检查请求负载,检查浏览器开发工具中的“网络”选项卡,找到您的请求并查看“标头”选项卡底部以查看“FormData”日志。你会看到这样的东西:
此外,您应该在 axios 中将标头“Content-Type”设置为“multipart/form-data”。这是工作示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<input type="file" multiple id="filepicker" />
<button id="send">Send</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js"></script>
<script>
const myformData = new FormData();
document
.querySelector('#filepicker')
.addEventListener('change', function (event) {
const { files } = event.target;
Object.values(files).forEach(function (file, index) {
myformData.append(index, file);
});
});
document.querySelector('#send').addEventListener('click', function () {
axios({
method: 'post',
url: 'http://google.com',
data: myformData,
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
});
</script>
</body>
</html>

TA贡献1821条经验 获得超5个赞
我在我的 React Native 应用程序上遇到了这个问题。为了解决它,我必须将图像路径转换为 blob。下面给出了我的句柄上传功能的代码。
const handleUpload = async () => {
if (selectedImage.localUri !== '') {
const image_uri = Platform.OS === 'ios' ? selectedImage.localUri.replace('file://', '') : selectedImage.localUri;
const response = await fetch(image_uri);
const blob = await response.blob();
const formData = new FormData();
formData.append('image', blob, "xray_image.jpg");
setLoading(true);
axios.post("https://...", formData)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
} else {
console.log("Select a file error message");
}
};

TA贡献1936条经验 获得超7个赞
export async function uploadImages(files, userId) {
try {
const images = new FormData();
for(const file of files){
images.append("image", file);
}
const res = await ax.post(process.env.SERVER_URL + "/upload-images", {
images,
userId,
});
return "success"
} catch (err) {
return "error"
}
}

TA贡献1863条经验 获得超2个赞
您必须将扩展名与名称一起传递
files[1] && images.append("image", files[1], "custom-name.jpg");
添加回答
举报