我正在使用axios点击一个API上传一个.apk文件到一个在我的计算机上本地运行的第三方应用程序上。在Postman上使用API得到了想要的结果,但在将其与我的React应用程序集成时,我得到了POST http://localhost:8000/api/v1/upload 400 (Bad Request)
错误。
我有以下结构:
- 源代码/http请求.js*
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8000",
headers: {
"Content-type": "application/json",
Authorization: <API_KEY>
}
});
- 源代码/服务/上载.js*
import http from "../httpRequest";
const upload = (file, onUploadProgress) => {
const formData = new FormData();
formData.append("file", file);
return http.post("/upload", formData, {
headers: {
"Content-Type": "multipart/form-data",
Authorization:
<API_KEY>
},
onUploadProgress,
});
};
export default {
upload,
};
- 源代码/组件/ApkUpload.js*
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const ApkUpload = () => {
const [selectedFiles, setSelectedFiles] = useState(undefined);
// eslint-disable-next-line no-unused-vars
const [currentFile, setCurrentFile] = useState(undefined);
const [progress, setProgress] = useState(0);
const [message, setMessage] = useState('');
const [fileDetails, setFileDetails] = useState([]);
const handleUpload = async () => {
const data = new FormData();
data.append('file', selectedFiles);
try {
const res = await axios.post('http://localhost:8000/api/v1/upload', data, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: <API_KEY>,
},
onUploadProgress: (progressEvent) => {
setProgress(parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total), 10));
},
});
} catch (err) {
if (err.response.status === 500) {
setMessage('There was a problem with the server');
} else {
setMessage(err.response.data.message);
}
}
};
const handleChange = (e) => {
setSelectedFiles(e.target.files);
setCurrentFile(e.target.files[0]);
};
useEffect(() => {
axios.get("http://localhost:8000/api/v1/scans", {
headers: {
Authorization:
<API_KEY>,
},
}).then(res => {
setFileDetails(res.data.content);
});
},[]);
return (
<div className="container">
// simple button calling above methods
</div>
);
};
export default ApkUpload;
我正在使用MobSF作为我的第三方应用程序,上传他们需要多部分/表格数据。
虽然使用 Postman 我能够得到想要的结果,但我不能这样做与我的前端。任何帮助有关这个问题将不胜感激!
1条答案
按热度按时间j0pj023g1#
在
handleUpload
函数中,selectedFiles
状态的类型是FileList
,但它应该是File
。如果您正在处理单个文件,则可以用途:
对于多个文件,您可以执行以下操作: