微信小程序上传图片功能

微信小程序图片上传

  1. 采用的是基于struct的Java后台服务器,所以接受图片是由struct完成。
  2. 首先,在微信开发中,微信有自带的API 中wx.uploadfile能实现多图片上传功能,实现代码如下:
wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        that.setData({
          imgurl: tempFilePaths[0]
        })
      }
    })
    formSubmit: function (e) {
    var that = this
    console.log(e.detail.value)
    var imgurl = that.data.imgurl;
    var value = e.detail.value
    wx.uploadFile({
      url:'http://localhost:8080/test/add-goods', //仅为示例
      filePath: imgurl,//要上传文件资源的路径
      name: 'file',//文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容
      //在Java后台的action中主要声明,见下面的服务器代码
      formData: {//HTTP 请求中其他额外的 form data
      //goods要以字符串的进行传输
		goods:JSON.stringify(e.detail.value),
		user:nickname
		
	  },
      success: function (res) {
        var data = res.data
        console.log(res)
        wx.showModal({
          title: '添加成功',
          content: '是否返回首页',
          success: function (res) {
            if (res.confirm) {
              wx.switchTab({
                url: '/page/component/index',
              })
            }
          }
        })
      },
  1. 服务器端通过struct接受,在action类中要实现fileFileName,fileContentType大码如下:
private File file;
private String fileFileName;
private String fileContentType;
实现getter和setter方法
.......
public String goods() throws IllegalStateException, IOException, ServletException{	
		req.setCharacterEncoding("UTF-8");
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		//得到文件途径,在Tomcat服务器的文件中 、完成文件上传的操作
//		 System.out.println(path);
        //创建一个服务器端的文件
 //    fileFileName是文件名
        File dest = new File(path,fileFileName);
        //把文件拷入到path+fileFileName对应路径的文件中
        FileUtils.copyFile(file,dest);
        //由于微信端的formdate是字符数类型,所以要转换成json
        Gson gson = new Gson();
        Map map = new HashMap();
        map = gson.fromJson(goods, map.getClass());
        //输出map如下
 //{"goods_name":"w","goods_category":"ww","market_price":"ww","store_count":"www","store_des":"www"}
       
//        System.out.println(map.get("goods_name"));
		return "null";
	}

本文的图片上传是基于struct的框架,若有错误请留言笔者。

你可能感兴趣的:(微信开发)