小编给大家分享一下微信小程序实现上传照片代码的案例分析,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
纸上谈坑
在我实现了这个功能之前,我讲讲我是怎么在这个坑里爬上来的:
我实现上传文件后端的接口的参数是String类型的
前台传的参数:https://cache.yisu.com/upload/information/20200804/112/168.png
但由于这张是本地照片url(外网无法访问),我后台拿到的是一个String类型,是没有办法是去识别这是一张图片的,访问不了这个数据,仅仅把它当做字符串而已。(低级错误)
代码实现
前言:后端接受文件有2种方式(参数): 1. MultipartFile 2.base64
微信上传文件的开发文档
小程序代码
<!-- index.wxml -->
<view>
<view>文件上传</view>
<view>
<input id="file" type="file" bindtap="uploader"></input>
</view>
</view>
// index.js
Page({
data: {
},
uploader: function () {
wx.chooseImage({
count: 1,
success: function(res) {
let imgPath = res.tempFilePaths[0]
wx.uploadFile({
url: 'http://localhost:8080/customerRegister/uploadPricture',
filePath: imgPath,
name: 'files',
success:res=>{
console.log(res)
}
})
}
})
},
})
java后端代码
@RequestMapping(value = "/customerRegister",produces = "application/json;charset=utf-8")
public class {
@RequestMapping("/uploadPricture")
@ResponseBody
public String uploadPricture(@RequestParam("file") MultipartFile[] file) throws IOException {
MultipartFile multipartFile = file[0];
System.out.println("图片名称:"+multipartFile.getOriginalFilename());
InputStream inputStream = multipartFile.getInputStream();
return "{"mas":"ok"}";
}
P.s. 注意:这是一个ssm项目,因此你需要在pom.xml中添加依赖和在springmvc.xml中添加以下代码(这个问题搞了我几个小时,因为少了上传文件的配置,就会导致multipartfile这个类失效)
<!--pom.xml 文件上传所需要的依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--springmvc.xml-->
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 指定所上传的总大小不能超过1T。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件 -->
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>
看完了这篇文章,相信你对微信小程序实现上传照片代码的案例分析有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。