0%

react native 上传图片,flask服务端接收保存

记录下flask接受图片的坑

先说下环境:
1.react native编码的移动APP客户端
2.flask建立的服务端

APP客户端中有个上传图片的需求,需要保存在服务端。用了个第三方开源截图库‘react-native-image-crop-picke’,搜了下用法,顺便拷了个上传的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
uploadImage =(url, params)=> {
return new Promise(function (resolve, reject) {
var ary = params.path.split('/');
let formData = new FormData();
let file = {uri: params.path, type: 'multipart/form-data', name: ary[ary.length-1]};
formData.append("file", file);

fetch('http://localhost:8010/birds/' + url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Encoding': 'identity'
},
body: JSON.stringify(formData),
}).then((response) => response.json())
.then((responseData)=> {
console.log('uploadImage', responseData);
resolve(responseData);
})
.catch((err)=> {
console.log('err', err);
reject(err);
});
});
};

服务端代码如下:

1
2
3
4
5
6
7
8
9
10
@app.route('/upload', methods=['POST'])
def upload():
# upload_file = request.files['image01']
upload_file = request.files["file"]
if upload_file and allowed_file(upload_file.filename):
filename = secure_filename(upload_file.filename)
upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
return 'hello, '+request.form.get('name', 'little apple')+'. success'
else:
return 'hello, '+request.form.get('name', 'little apple')+'. failed'

那么坑爹的来了,获取的‘request.files[“file”]’没有值,各种翻墙爬楼,无果。
郁闷至极,自己分析了下,最终发现问题出在上面上传的参数,不过,postman也是失败,看来是flask的接收方式和其它resetful方式不一样。
改了下上传方式,终于解决了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
uploadImage =(url, params)=> {
return new Promise(function (resolve, reject) {
var ary = params.path.split('/');
let formData = new FormData();
let file = {uri: params.path, type: 'multipart/form-data', name: ary[ary.length-1]};
formData.append("file", file);

fetch('http://localhost:8010/birds/' + url, {
method: 'POST',
headers: {
},
body: formData,
}).then((response) => response.json())
.then((responseData)=> {
console.log('uploadImage', responseData);
resolve(responseData);
})
.catch((err)=> {
console.log('err', err);
reject(err);
});
});
};