微信小程序之上传图片(含前后端代码例子)

此代码示例,能够让你成功将图片上传至后端,后端做相应的处理,然后返回成功码。

前端小程序代码

index.wxml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<view class='content'>
<view class='img-box'>
<view class='img-list'>
<block wx:for="{{detailPics}}" wx:key="index">
<view class='img-item'>
<image src='{{item}}' bindlongpress="bindlongpressimg" data-id='{{index}}'></image>
</view>
</block>
<view class='chooseimg' bindtap='uploadDetailImage'>
<view class="weui-uploader__input-box"></view>
</view>
</view>
<view class='tips'>长按对应的图片即可删除</view>
</view>
</view>

index.wxss:

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
.content {
width: 100%;
background-color: #fff;
}

.img-list {
display: flex;
display: -webkit-flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
flex-wrap: wrap;
}

.img-item {
width: 30%;
text-align: left;
margin-right: 20rpx;
margin-bottom: 10rpx;
}

.img-item image {
width: 180rpx;
height: 180rpx;
}

.submit-btn {
width: 100%;
background-color: #fff;
height: 80rpx;
text-align: center;
line-height: 80rpx;
font-size: 30rpx;
position: fixed;
bottom: 100rpx;
}

.chooseimg {
background-color: #fff;
}

.weui-uploader__input-box {
float: left;
position: relative;
margin-right: 9px;
margin-bottom: 9px;
width: 180rpx;
height: 180rpx;
border: 1px solid #d9d9d9;
}

.weui-uploader__input-box:before {
width: 2px;
height: 39.5px;
}

.weui-uploader__input-box:after, .weui-uploader__input-box:before {
content: " ";
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #d9d9d9;
}

.weui-uploader__input-box:after {
width: 39.5px;
height: 2px;
}

.weui-uploader__input-box:after, .weui-uploader__input-box:before {
content: " ";
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #d9d9d9;
}

.tips {
color: #666;
font-size: 24rpx;
padding-bottom: 20rpx;
}

.img-box {
width: 92%;
margin: auto;
padding-top: 20rpx;
}

index.js:

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// component/uploadImages/index.js
Component({
/**
* 组件的属性列表
*/
properties: {
count: { //最多选择图片的张数,默认9张
type: Number,
value: 9
},
uploadUrl: { //图片上传的服务器路径
type: String,
value: ''
},
showUrl: { //图片的拼接路径
type: String,
value: ''
}
},

/**
* 组件的初始数据
*/
data: {
detailPics: [], //上传的结果图片集合
},

ready: function () {
console.log(this.data)
},

/**
* 组件的方法列表
*/
methods: {

uploadDetailImage: function (e) { //这里是选取图片的方法
var that = this;
var pics = [];
var detailPics = that.data.detailPics;
if (detailPics.length >= that.data.count) {
wx.showToast({
title: '最多选择' + that.data.count + '张!',
})
return;
}
wx.chooseImage({
count: that.data.count, // 最多可以选择的图片张数,默认9
sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
success: function (res) {
var imgs = res.tempFilePaths;
for (var i = 0; i < imgs.length; i++) {
pics.push(imgs[i])
}
that.uploadimg({
url: "http://www.test.com//test-api/wechat/applet/api/uploadUserAvatar", //这里是你图片上传的接口
path: pics, //这里是选取的图片的地址数组
});
},
})

},
//多张图片上传
uploadimg: function (data) {
wx.showLoading({
title: '上传中...',
mask: true,
})
var that = this,
i = data.i ? data.i : 0,
success = data.success ? data.success : 0,
fail = data.fail ? data.fail : 0;
wx.uploadFile({
url: data.url,
filePath: data.path[i],
name: 'file',
formData: {"userId":"35"},
success: (resp) => {
wx.hideLoading();
success++;
var str = resp.data //返回的结果,可能不同项目结果不一样

console.log(str);
// var pic = JSON.parse(str);
// var pic_name = that.data.showUrl + pic.Data;
// var detailPics = that.data.detailPics;
// detailPics.push(pic_name)
// that.setData({
// detailPics: detailPics
// })
},
fail: (res) => {
fail++;
console.log('fail:' + i + "fail:" + fail);
},
complete: () => {
i++;
if (i == data.path.length) { //当图片传完时,停止调用
console.log('执行完毕');
console.log('成功:' + success + " 失败:" + fail);
var myEventDetail = {
picsList: that.data.detailPics
} // detail对象,提供给事件监听函数
var myEventOption = {} // 触发事件的选项
that.triggerEvent('myevent', myEventDetail, myEventOption)//结果返回调用的页面
} else { //若图片还没有传完,则继续调用函数
data.i = i;
data.success = success;
data.fail = fail;
that.uploadimg(data);//递归,回调自己
}
}
});
},

}
})

后端Java代码(这里我使用的是第三方存储,如腾讯云,如果读者朋友们是使用第三方存储替换是一件很容易的事情)

核心代码如下:

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
@PostMapping("/uploadUserAvatar")
@ApiOperation(value = "上传用户头像", notes = "上传用户头像")
public JSONObject uploadUserAvatar(HttpServletRequest request) {

JSONObject json = new JSONObject();
try {

String userId = request.getParameter("userId");

COSClientUtil cosClientUtil = new COSClientUtil();

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

// 获取上传的文件
MultipartFile multiFile = multipartRequest.getFile("file");



String name = cosClientUtil.uploadFileCos(multiFile);

// 获取文件路径
String fileUrl = cosClientUtil.getFileUrl(name);

Console.log("fileUrl:"+fileUrl);


// 对文件路径进行处理
String dbFileUrl = fileUrl.substring(0, fileUrl.indexOf("?"));


Console.log("dbFileUrl:"+dbFileUrl);

User user = new User();
user.setId(Integer.parseInt(userId));
user.setSmallAvatar(dbFileUrl);

boolean isUploadUserAvatar = userService.updateById(user);

if (isUploadUserAvatar) {
json.put(ResponseUtils.CODE, ResponseUtils.SUCCESS_CODE);
json.put(ResponseUtils.MSG, ResponseUtils.SUCCEESS_MSG);
} else {
json.put(ResponseUtils.CODE, ResponseUtils.ERROR_CODE);
json.put(ResponseUtils.MSG, ResponseUtils.ERROR_MSG);
}

} catch (Exception e) {
e.printStackTrace();

json.put(ResponseUtils.CODE, ResponseUtils.ERROR_CODE);
json.put(ResponseUtils.MSG, ResponseUtils.ERROR_MSG);

}

return json;
}

文章目录
  1. 前端小程序代码
  2. 后端Java代码(这里我使用的是第三方存储,如腾讯云,如果读者朋友们是使用第三方存储替换是一件很容易的事情)