小程序笔记(8)文件上传

小程序文件上传

微信小程序代码

需要注意的一些参数

name: "file", // 这个参数对应表单的那个文件名称,在后端获取的时候需要要这个参数

formData:// 这是文件附带的数据

success: function (res)// 无论成功与否都会执行这个函数

sourceType: ['album', 'camera']// 可以指定来源是相册还是相机,默认二者都有

使用springmvc+小程序来的的的的!!!!!!

选择图片

  //选择文件
  chooseImage: function () {
    var that = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        let src = res.tempFilePaths[0]
        that.setData({
          src: src
        })
      }
    })
  }

开始上传

uploadFile: function () {
    var that = this
    //获取图片路径地址
    let src = this.data.src;
    let title = this.data.title;
    let price = this.data.price;
    //尚未选择图片
    if (src == '') {
      wx.showToast({
        title: '请先选择文件!',
        icon: 'none'
      })
    }
    //准备上传文件
    else {
      //发起文件上传请求
      var uploadTask = wx.uploadFile({
        url: 'http://172.16.80.145:8080/tmall/home/upload',
        filePath: src,
        name: "file", // 这个参数对应表单的那个文件名称,在后端获取的时候需要要这个参数
        formData: {// 这是文件附带的数据
          title: title,
          price: price
        },
        success: function (res) { // 无论成功与否都会执行这个函数
          console.log(res)
          wx.showToast({
            title: res.data
          })
        }
      })
    }
  }

后端代码

后端使用springmvc来接收

pom文件

 <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>

springmvc.xml文件配置

   <!-- 文件上传配置 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 上传文件大小限制为31M,31*1024*1024 -->
        <property name="maxUploadSize" value="32505856"/>
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="4096"/>
   </bean>

Controller代码

 @ResponseBody
    @RequestMapping("/upload")
    public String upload(HttpServletRequest request , @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        System.out.println("执行upload");
        request.setCharacterEncoding("UTF-8");
        System.out.println("执行图片上传");
        String title = request.getParameter("title");
        String price = request.getParameter("price");
        System.out.println("title:" + title);
        System.out.println("price:" + price);
        if (!file.isEmpty()) {
            System.out.println("成功获取照片");
            String fileName = file.getOriginalFilename();
            String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1 , fileName.length()) : null;
            System.out.println("图片初始名称为:" + fileName + " 类型为:" + type);
            if (type != null) {
                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置存放图片文件的路径
                    path = "G:" + "/uploads/" + trueFileName;
                    System.out.println("存放图片文件的路径:" + path);
                    file.transferTo(new File(path));
                    System.out.println("文件成功上传到指定目录下");
                } else {
                    System.out.println("不是我们想要的文件类型,请按要求重新上传");
                    return "error";
                }
            } else {
                System.out.println("文件类型为空");
                return "error";
            }
        } else {
            System.out.println("没有找到相对应的文件");
            return "error";
        }
        return "success";
    }

一些错误

	org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'multipartResolver': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.web.multipart.commons.CommonsMultipartResolver] from ClassLoader [ParallelWebappClassLoader
  context: tmall
  delegate: false
----------> Parent Classloader:
java.net.URLClassLoader@79e2c065
]
  • 可能是由于jar包没导,也就是要重新加载一下maven

  • maven加载完成之后,还是不行,可能是jar包没有在当前工程下,按照以下操作就好了

    image-20201030182526903

image-20201030182615090

  • 全选导入就好了

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ja1G6V1B-1604053712543)(https://i.loli.net/2020/10/30/1iR59enEFL6YlfW.png)]

运行结果

image-20201030182701504

image-20201030182707253

image-20201030182723648

image-20201030182737268

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值