您好,我正在尝试从我从烧瓶后端的 send_file 获得的二进制响应中创建一个 javascript 文件对象。
烧瓶端点
@app.route('/costTracker/file', methods=['POST'])
def costTrackerFile(token=None):
body = request.get_json(force=True)
if body.get('FILENAME', None) is None:
return response(400, 'No Filename found', token)
filename = body.get('ATTACHMENT', 'FILENAME')
return send_file(os.path.join(
app.config['UPLOAD_FOLDER'], body.get('FOLDER', ''), body['FILENAME']), attachment_filename=filename)
使用 axios 进行响应
const [file,setFile] = React.useState<File | undefined>(undefined);
...
await axios.post('/costTracker/file',{
FILENAME: '5c466663cc535cd3501e5aec495400b9af57235c581ac4e4fc1dc6d6792f2646.png',
ATTACHMENT: 'MicrosoftTeams-image.png',
FOLDER: 'CostTracker'
}).then(resp => {
const { data } = resp;
var f = new File([data], 'filename.png')
console.log(f);
setFile(f);
})
答案 0 :(得分:0)
关键是在 axios 调用中将 responseType 参数设置为“blob”,然后根据响应创建文件对象。
axios
.get('/download', { params, responseType: 'blob' })
.then((resp) => {
const file = new File(
[resp.data],
params.attachment ?? params.filename
);
const ops_file: OPSFile = {
id: params.id,
file,
message: 'file uploaded successfully',
progress: 100,
statusCode: 100,
};
setUploads((old) => [
...old.filter(({ id }) => id !== params.id),
ops_file,
]);
});