网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

纸上谈坑

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

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

前台传的参数:http://tmp/wx忽略很多字母数字.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>

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

上一篇:vue flex 布局实现div均分自动换行的示例代码
下一篇:JavaScript实现烟花绽放动画效果
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网