javascript - 烧瓶 send_file 到 Javascript 文件对象
问题描述
您好,我正在尝试根据我从烧瓶后端的 send_file 获得的二进制响应在 javascript 中创建一个 File 对象。
烧瓶端点
@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);
})
解决方案
关键是在 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,
]);
});
推荐阅读
- javascript - 如何在 ReactJs 的复选框中显示星期几
- protractor - 检查量角器黄瓜框架中是否存在元素
- c++ - 我有两组数据相互映射。有没有办法根据另一个变量的值检查相应变量的值?
- arrays - 如何在c中水平查找二维数组(10x2)中的重复值
- java - EditText 没有出现在模拟器中
- matomo - 当参数包含大写字母时,Matomo Track 事件不起作用
- php - 如何将txt文件中的内容获取到数组中
- firebase - 使用firebase在flutter中安排通知
- java - 如何在 intelliJ 中切换 java 版本?
- css - 如何使 React Material-UI Accordion 填充整个高度?