前言
最近在做微信小程序开发,用到了通过微信小程序上传图片到服务器的一个功能,下面分享给大家。
小程序端
chooseImage: function () {
var openid = wx.getStorageSync("openid");
var that = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
console.log(tempFilePaths[0]);
wx.uploadFile({
url: app.globalData.mainServer + 'ApiController/uploadImgFile.do', //此处换上你的接口地址
filePath: tempFilePaths[0],
name: 'img',
header: {
"Content-Type": "multipart/form-data",
'accept': 'application/json'
},
formData: {},
success: function (res) {
console.log(res)
var data = JSON.parse(res.data)[0].info;
data = data.replace(app.globalData.mainServer,'');
that.setData({
picUrl:data
})
},
fail: function (res) {
console.log('fail');
},
})
}
})
}
说明:上面代码中app.globalData.mainServer是接口调用地址的前缀,res.data.info存储的是已经上传的图片的网络地址,包含域名部分。
服务端Java处理代码
@RequestMapping(value="/uploadImgFile.do",method={RequestMethod.GET,RequestMethod.POST})
public String uploadImgFile(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
Map<String,Object> m = new HashMap<String,Object>();
JSONArray resultJson = new JSONArray();
String mainServer = this.apiService.findValueByNameAdmin("mainServer", "admin");
MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;
MultipartFile multipartFile = req.getFile("img");
String realPath = request.getServletContext().getRealPath("/upload/");
String imgName =UUID.randomUUID().toString()+".jpg";
String imgPath = mainServer+"upload/"+imgName;
try {
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(realPath,imgName);
multipartFile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
m.put("info", imgPath);
JsonConfig config = new JsonConfig();
JsonDateValueProcessor jsonValueProcessor = new JsonDateValueProcessor();
config.registerJsonValueProcessor(Date.class, jsonValueProcessor);
resultJson = JSONArray.fromObject(m,config);
try
{
BufferedWriter out = null;
out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
out.write(resultJson.toString());
out.flush();
}
catch (IOException e){
e.printStackTrace();
}
return null;
}
微信小程序上传图片-有没有可以上传视频的小程序
浏览量:5675
时间:
来源:跟我一起学编程
版权声明
即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。
最新资讯
-
抖音再现本地生活服务,咫尺同城圈商业变现新通道
短视频成为本地生活探店网红营销变现引流的新阵地,每一位网红都渴望在短视频内“一夜爆红”。即速应用团队对多商家小程序进行升级,打造了咫尺同城圈:“同城探店营销助手”,不仅完善商家营销技巧,还助力探店网红玩转本地生活服务。 -
抖音再现本地生活服务,咫尺同城圈商业变现新通道
短视频成为本地生活探店网红营销变现引流的新阵地,每一位网红都渴望在短视频内“一夜爆红”。即速应用团队对多商家小程序进行升级,打造了咫尺同城圈:“同城探店营销助手”,不仅完善商家营销技巧,还助力探店网红玩转本地生活服务。 -
阿坝小程序代理
阿坝藏族羌族小程序代理公司有哪些?阿坝藏族羌族小程序代理平台哪个好?阿坝藏族羌族小程序代理商怎么收费,代理政策如何?下面就让即速应用产品经理jisuapp.cn来告诉你吧!