如果不想要服务端实现处理base64格式的图片的转换,那么在浏览器端来实现,部分属于伪代码, 且 axios 未封装处理,仅作为开发参考,请勿直接拷贝使用 ?
代码封装
主要通过react来实现,下面是封装之后的上传方法,仅作为开发参考
复制代码
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58uploadPic(base64String, suc, fail) { // 下面将要把 base64 转换成formdata // 这里对base64串进行操作,去掉url头,并转换为byte let bytes = window.atob(base64String.split(',')[1]); let array = []; for(let i = 0; i < bytes.length; i++){ array.push(bytes.charCodeAt(i)); } let blob = new Blob([new Uint8Array(array)], {type: 'image/jpeg'}); // 生成FormData对象 let fd = new FormData(); // 注:此处 file 应和后台接收参数匹配 fd.append('file', blob, Date.now() + '.jpg'); let config = { headers: {'Content-Type': 'multipart/form-data'} } let url = Constant.fileUrl; // 加载中 this.setState({ loadingShow: true, loadingText: '图片上传中...', }); // 添加请求头 axios.post(url, fd, config) .then(response => { if(response.data.resultcode === 200) { suc && suc(response.data.content[0]); } else { fail && fail(response.data.resultmsg); } }) .catch(() => { fail && fail('网络原因, 未上传成功!'); }); } // 把图片保存到服务器端 savePic(imgUrl, suc, fail) { // 添加请求头 let url = Constant.appServerUrl + "/file-save"; let postData = { protocolImg: imgUrl, puid: Storage.get('uid') }; axios.post(url, postData) .then(response => { if(response.data.resultcode === 200) { suc && suc(response.data); } else { fail && fail(response.data); } }) .catch(() => { fail && fail('网络原因, 未保存成功!'); }); }
函数调用
复制代码
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
26
27
28
29
30
31// 上传base64的图片 this.uploadPic(base64String, (url) => { // 成功的回调 this.setState({ loadingText: '图片保存中...', }); // 保存图片 this.savePic(url, (msg)=>{ // console.log('msg', msg); // 保存成功,提示 this.setState({ loadingText: '请稍后...', isProtocol: true, }); // 开始进行支付操作 // this.clickToPayForOrder(); }, (error)=>{ // 保存失败 提示: alert('图片保存失败: ' + error); }); }, (errMsg) => { // 失败的回调 alert("发生错误: ", errMsg); // loading 消失 this.setState({ loadingShow: false, loadingText: '' }); });
最后
以上就是清脆睫毛最近收集整理的关于在react中 实现 base64的图片转换成formdata格式并实现上传功能的全部内容,更多相关在react中内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复