我是靠谱客的博主 精明音响,这篇文章主要介绍微信小程序内实现上传图片附后端代码,现在分享给大家,希望可以做个参考。

这次给大家带来微信小程序内实现上传图片附后端代码,微信小程序内实现上传图片的注意事项有哪些,下面就是实战案例,一起来看一下。

当然小程序也是可以上传图片的,微信小程序文档也写的很清楚。

上传图片

首先选择图片

通过wx.chooseImage(OBJECT)实现

官方示例代码

复制代码
1
2
3
4
5
6
7
8
9
wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths } })
登录后复制

图片最多可以选择9张, 也可以通过拍摄照片实现,当选择完图片之后会获取到图片路径, 这个路径在本次启动期间有效。
如果需要保存就需要用wx.saveFile(OBJECT)

上传图片

通过wx.uploadFile(OBJECT) 可以将本地资源文件上传到服务器。

原理就是客户端发起一个 HTTPS POST 请求,其中 content-type为 multipart/form-data。

官方示例代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
wx.chooseImage({ success: function(res) { var tempFilePaths = res.tempFilePaths wx.uploadFile({ url: 'http://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址 filePath: tempFilePaths[0], name: 'file', formData:{ 'user': 'test' }, success: function(res){ var data = res.data //do something } }) } })
登录后复制

示例代码

看完了官方文档, 写一个上传图片就没有那么麻烦了,下面是真实场景的代码

复制代码
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
import constant from '../../common/constant'; Page({ data: { src: "../../image/photo.png", //绑定image组件的src //略... }, onLoad: function (options) { //略... }, uploadPhoto() { var that = this; wx.chooseImage({ count: 1, // 默认9 sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths; upload(that, tempFilePaths); } }) } }) function upload(page, path) { wx.showToast({ icon: "loading", title: "正在上传" }), wx.uploadFile({ url: constant.SERVER_URL + "/FileUploadServlet", filePath: path[0], name: 'file', header: { "Content-Type": "multipart/form-data" }, formData: { //和服务器约定的token, 一般也可以放在header中 'session_token': wx.getStorageSync('session_token') }, success: function (res) { console.log(res); if (res.statusCode != 200) { wx.showModal({ title: '提示', content: '上传失败', showCancel: false }) return; } var data = res.data page.setData({ //上传成功修改显示头像 src: path[0] }) }, fail: function (e) { console.log(e); wx.showModal({ title: '提示', content: '上传失败', showCancel: false }) }, complete: function () { wx.hideToast(); //隐藏Toast } }) }
登录后复制

后端代码

后端是用java写的,一开始的时候,后端开始用了一些框架接收上传的图片,出现了各种问题,后来使用了纯粹的Servlet就没有了问题, 把代码贴出来省的以后麻烦了。

注意: 代码使用了公司内部的框架,建议修改后再使用

复制代码
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
public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger logger = LoggerFactory.getLogger(FileUploadServlet.class); public FileUploadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonMessage<Object> message = new JsonMessage<Object>(); EOSResponse eosResponse = null; String sessionToken = null; FileItem file = null; InputStream in = null; ByteArrayOutputStream swapStream1 = null; try { request.setCharacterEncoding("UTF-8"); //1、创建一个DiskFileItemFactory工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、创建一个文件上传解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解决上传文件名的中文乱码 upload.setHeaderEncoding("UTF-8"); // 1. 得到 FileItem 的集合 items List<FileItem> items = upload.parseRequest(request); logger.info("items:{}", items.size()); // 2. 遍历 items: for (FileItem item : items) { String name = item.getFieldName(); logger.info("fieldName:{}", name); // 若是一个一般的表单域, 打印信息 if (item.isFormField()) { String value = item.getString("utf-8"); if("session_token".equals(name)){ sessionToken = value; } }else { if("file".equals(name)){ file = item; } } } //session校验 if(StringUtils.isEmpty(sessionToken)){ message.setStatus(StatusCodeConstant.SESSION_TOKEN_TIME_OUT); message.setErrorMsg(StatusCodeConstant.SESSION_TOKEN_TIME_OUT_MSG); } String userId = RedisUtils.hget(sessionToken,"userId"); logger.info("userId:{}", userId); if(StringUtils.isEmpty(userId)){ message.setStatus(StatusCodeConstant.SESSION_TOKEN_TIME_OUT); message.setErrorMsg(StatusCodeConstant.SESSION_TOKEN_TIME_OUT_MSG); } //上传文件 if(file == null){ }else{ swapStream1 = new ByteArrayOutputStream(); in = file.getInputStream(); byte[] buff = new byte[1024]; int rc = 0; while ((rc = in.read(buff)) > 0) { swapStream1.write(buff, 0, rc); } Usr usr = new Usr(); usr.setObjectId(Integer.parseInt(userId)); final byte[] bytes = swapStream1.toByteArray(); eosResponse= ServerProxy.getSharedInstance().saveHeadPortrait(usr, new RequestOperation() { @Override public void addValueToRequest(EOSRequest request) { request.addMedia("head_icon_media", new EOSMediaData(EOSMediaData.MEDIA_TYPE_IMAGE_JPEG, bytes)); } }); // 请求成功的场合 if (eosResponse.getCode() == 0) { message.setStatus(ConstantUnit.SUCCESS); } else { message.setStatus(String.valueOf(eosResponse.getCode())); } } } catch (Exception e) { e.printStackTrace(); } finally{ try { if(swapStream1 != null){ swapStream1.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(in != null){ in.close(); } } catch (IOException e) { e.printStackTrace(); } } PrintWriter out = response.getWriter(); out.write(JSONObject.toJSONString(message)); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
登录后复制

相信看了本文案例你已经掌握了方法,更多精彩请关注靠谱客其它相关文章!

推荐阅读:

关于js的三种使用方式案例详解(附代码)

如何使用微信小程序做出图片上传

以上就是微信小程序内实现上传图片附后端代码的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是精明音响最近收集整理的关于微信小程序内实现上传图片附后端代码的全部内容,更多相关微信小程序内实现上传图片附后端代码内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(112)

评论列表共有 0 条评论

立即
投稿
返回
顶部