赞
踩
UpImages.wxml
<button bindtap='uploadPhoto'>拍照选取照片上传</button>
简单画一个页面,使用按钮调小程序默认的upload(page, path)方法,默认支持单次上传一张图片,可修改
Upimages.js
Page({ data: { imgData: [] }, uploadPhoto() { // 拍摄或从相册选取上传 let that = this; wx.chooseImage({ count: 1, // 默认9 sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success(res) { let tempFilePaths = res.tempFilePaths; // 返回选定照片的本地路径列表 that.upload(that, tempFilePaths); } }) }, upload(page, path) { // 上传图片 wx.showToast({ icon: "loading", title: "正在上传……" }); wx.uploadFile({ url: '', //本地后端接口 filePath: path[0], name: 'file', header: { "Content-Type": "multipart/form-data" //必须是multipart/form-data格式才能上传文件 }, formData: { //和服务器约定的token, 一般也可以放在header中 'session_token': wx.getStorageSync('session_token') }, success(res) { console.log(res) if (res.statusCode != 200) { wx.showModal({ title: '提示', content: '上传失败', showCancel: false }); return; } else { wx.showModal({ title: '提示', content: '上传成功', success: function (res) { if (res.confirm) { //这里是点击了确定以后 console.log('用户点击确定') wx.navigateTo({ url: "../index/index" //这里是上传成功后确定返回页面 }) } else { //这里是点击了取消以后 console.log('用户点击取消') wx.navigateTo({ url: "../index/index" //这里是上传成功后取消返回页面 }) } } }) } }, fail(e) { wx.showModal({ title: '提示', content: '上传失败', showCancel: false }); }, complete() { wx.hideToast(); //隐藏Toast } }) } })
我目前使用的是SSM框架,需要在springmvc.xml添加配置
springmvc.xml
<!-- 配置文件上传相关 --> <!--配置文件解析器对象,有了它就可以进行文件上传--> <!-- 配置文件解析器--> <!-- 此处id为固定写法,不能随便取名--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="1048576"></property> </bean>
- //接收小程序上传的图片
- @RequestMapping(value = "/upload", method = {RequestMethod.POST, RequestMethod.GET})
- @ResponseBody
- public String[] uploadfile(MultipartFile[] file, HttpServletRequest request) {
- //本地服务器图片文件地址
- String dir = "D:\\images";
- String[] b = null;
- for (MultipartFile files : file) {
- String filename = files.getOriginalFilename();
- String suffix = filename.substring(filename.lastIndexOf("."));
- String path = filename;
- //创建要保存文件的路径
- String time = new Date().getTime() + "." + suffix;
- String[] a = {path, time};
- File dirFile = new File(dir, time);
- if (!dirFile.exists()) {
- dirFile.mkdirs();
- }
- try {
- //将文件写入创建的路径
- files.transferTo(dirFile);
- return a;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return b;
- }
记得最重要的一点:小程序的名称file和后台Controller接收的名称file必须一致才能把图片传输到后台
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。