python-3.x - Axios 烧瓶。解析fileblob和json
问题描述
我们需要同时向服务器发送json with userId
和发送file
。客户端使用Axios库。
const userId = this.$store.getters['login/userId'];
const obj = {
userId: userId
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const fd = new FormData();
const vue = this;
async function submitAllFiles(){
let file = vue.files[0];
fd.append('file', file);
fd.append(userId, blob);
const options = {
onUploadProgress: (progressEvent) => {
...
}
};
await vue.axios
.post('http://127.0.0.1:5000/upload_to_db', fd, options)
.then((response) => {
console.log(response);
})
这是处理的服务器部分
@api.route('/upload_to_db', methods=['POST'])
@cross_origin()
def upload_to_db():
print('Trying to upload file')
print(request.files)
teacher_id = request.files.getlist('userId')
# teacher_id = json.load(request.files['userId'])
# print(teacher_id.get('blob'))
files = request.files.getlist('file')
print(files)
if insert_pdf_into_table(teacher_id,
files[0]):
return jsonify({'result': True})
# print('Sending request to /simple_check')
return jsonify({'result': False})
由于我们可以使用标准 files[0].filename 和 files[0].read() 轻松解析 file-part 但是我们如何解析 json-part 呢?
解决方案
您不需要使用 Blob。只需附加到 formData 对象。
客户端:
const userId = this.$store.getters['login/userId'];
const fd = new FormData();
const vue = this;
async function submitAllFiles(){
let file = vue.files[0];
fd.append('file', file);
fd.append(userId, userId);
const options = {
onUploadProgress: (progressEvent) => {
...
}
};
await vue.axios
.post('http://127.0.0.1:5000/upload_to_db', fd, options)
.then((response) => {
console.log(response);
})
服务器端:
@api.route('/upload_to_db', methods=['POST'])
@cross_origin()
def upload_to_db():
user_id = request.form.get('userId')
files = request.files.getlist('file')
if insert_pdf_into_table(
user_id=user_id,
filename=files[0]):
return jsonify({'result': True})
return jsonify({'result': False})
推荐阅读
- linux-kernel - 单独编译后无法加载内核模块
- python - 如何将数据框转换为列表而不在python中添加更多小数位
- vb.net - 将 msi 提取到 Visual Basic.net
- kotlin - 我可以将构建器模式与 lambda 表达式结合起来吗?
- c++ - 在文件中查找并提取某个值
- python-3.x - Shifting x axis in dataframe.plot() : Python
- java - 如何在没有 web.xml 的情况下应用 ContainerRequestFilter?
- c++ - Cesanta Mongoose - 连接到本地主机时出现问题
- python - 如何根据其他列的内容选择数据框中的特定数据?
- c# - 从 ASP.NET mvc 中的数组下拉列表