How to use WeChat applet to upload pictures

php中世界最好的语言
Release: 2018-05-31 14:10:16
Original
11288 people have browsed it

This time I will show you how to use the WeChat applet to upload pictures. What are the precautions for using the WeChat applet to upload pictures? The following is a practical case. Let’s take a look.

Let’s take a look at the API of the WeChat applet

Let’s take a look at the page effect

View large image

wxml file code:

<view class="weui-cell"> 
    <view class="weui-cellbd"> 
     <view class="weui-uploader"> 
      <view class="weui-uploaderhd"> 
       <view class="weui-uploadertitle">营业执照</view> 
       <view class="weui-uploaderinfo">{{imageList.length}}/{{count[countIndex]}}</view> 
      </view> 
      <view class="weui-uploaderbd"> 
       <view class="weui-uploaderfiles"> 
        <block wx:for="{{imageList}}" wx:for-item="image"> 
         <view class="weui-uploaderfile"> 
          <image class="weui-uploaderimg" src="{{image}}" src="{{image}}" bindtap="previewImage"></image> 
         </view> 
        </block> 
       </view> 
       <view class="weui-uploaderinput-box"> 
        <view class="weui-uploaderinput" bindtap="chooseImage"></view> 
       </view> 
      </view> 
     </view> 
  </view> 
</view>
Copy after login

js file code

chooseImage: function () { 
  var that = this; 
  console.log('aaaaaaaaaaaaaaaaaaaa') 
  
  wx.chooseImage({ 
   count: this.data.count[this.data.countIndex], 
   success: function (res) { 
    console.log('ssssssssssssssssssssssssss') 
    //缓存下 
    wx.showToast({ 
     title: '正在上传...', 
     icon: 'loading', 
     mask: true, 
     duration: 2000, 
     success: function (ress) { 
      console.log('成功加载动画'); 
     } 
    }) 
 
    console.log(res) 
    that.setData({ 
     imageList: res.tempFilePaths 
    }) 
    //获取第一张图片地址 
    var filep = res.tempFilePaths[0] 
    //向服务器端上传图片 
    // getApp().data.servsers,这是在app.js文件里定义的后端服务器地址 
    wx.uploadFile({ 
     url: getApp().data.servsers + '/weixin/wx_upload.do', 
     filePath: filep, 
     name: 'file', 
     formData: { 
      'user': 'test' 
     }, 
     success: function (res) { 
      console.log(res) 
      console.log(res.data) 
      var sss= JSON.parse(res.data) 
      var dizhi = sss.dizhi; 
      //输出图片地址 
      console.log(dizhi); 
      that.setData({ 
       "dizhi": dizhi 
      }) 
 
      //do something  
     }, fail: function (err) { 
      console.log(err) 
     }  
      }); 
   } 
  }) 
 }, 
 previewImage: function (e) { 
  var current = e.target.dataset.src 
 
  wx.previewImage({ 
 
   current: current, 
   urls: this.data.imageList 
  }) 
 }
Copy after login

java Back-end code:

//获取当前日期时间的string类型用于文件名防重复 
  public String dates(){ 
     Date currentTime = new Date(); 
     SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); 
     String dateString = formatter.format(currentTime); 
     return dateString; 
  } 
  @RequestMapping("wx_upload.do") 
  public void uploadPicture(HttpServletRequest request, HttpServletResponse response,PrintWriter writer) throws Exception { 
    System.out.println("进入get方法!"); 
  //获取从前台传过来得图片 
    MultipartHttpServletRequest req =(MultipartHttpServletRequest)request; 
    MultipartFile multipartFile = req.getFile("file"); 
  //获取图片的文件类型 
    String houzhu=multipartFile.getContentType(); 
    int one = houzhu.lastIndexOf("/"); 
    System.out.println(houzhu.substring((one+1),houzhu.length())); 
    System.out.println(multipartFile.getName()); 
  //根据获取到的文件类型截取出图片后缀 
    String type=houzhu.substring((one+1),houzhu.length()); 
    System.out.println(multipartFile.getContentType()); 
 
    String filename; 
  // request.getRealPath获取我们项目的根地址在加上我们要保存的地址 
    String realPath = request.getRealPath("/upload/wximg/"); 
    try { 
      File dir = new File(realPath); 
      if (!dir.exists()) { 
        dir.mkdir(); 
      } 
      //获取到当前的日期时间用户生成文件名防止文件名重复 
      String filedata=this.dates(); 
    //生成一个随机数来防止文件名重复 
      int x=(int)(Math.random()*1000); 
      filename="zhongshang"+x+filedata; 
      System.out.println(x); 
    将文件的地址和生成的文件名拼在一起 
      File file = new File(realPath,filename+"."+type); 
      multipartFile.transferTo(file); 
    //将图片在项目中的地址和isok状态储存为json格式返回给前台,由于公司项目中没有fastjson只能用这个 
      JSONObject jsonObject=new JSONObject(); 
      jsonObject.put("isok",1); 
      jsonObject.put("dizhi","/upload/wximg/"+filename+"."+type); 
 
      writer.write(jsonObject.toString()); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } catch (IllegalStateException e) { 
      e.printStackTrace(); 
    } 
}
Copy after login

Let’s take a look at the content previously output in the front-end js:

Open the browser and use our Add the address of the server and the dizhi field of json returned in the background to access this picture

We can see that the picture has been filled in our server, and then open our /upload/wximg

# under the root address of the server-side project is done here. If you want to upload multiple pictures, you can upload them in js in a loop according to the number to be uploaded.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the three usage methods of js (with code)

Usage of JS loading method Summary

The above is the detailed content of How to use WeChat applet to upload pictures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!