微信小程序实现上传照片代码实例解析

纸上谈坑

在我实现了这个功能之前,我讲讲我是怎么在这个坑里爬上来的:

我实现上传文件后端的接口的参数是String类型的

前台传的参数:http://img.laike.net/1022120532101984teu45qhssf.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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。