Home WeChat Applet Mini Program Development How to use WeChat applet to upload pictures

How to use WeChat applet to upload pictures

May 31, 2018 pm 02:10 PM
picture Applets

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? Mar 22, 2024 am 08:06 AM

How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting?

How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? Mar 21, 2024 pm 09:12 PM

How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area?

6 Ways to Make Pictures Sharper on iPhone 6 Ways to Make Pictures Sharper on iPhone Mar 04, 2024 pm 06:25 PM

6 Ways to Make Pictures Sharper on iPhone

How to make ppt pictures appear one by one How to make ppt pictures appear one by one Mar 25, 2024 pm 04:00 PM

How to make ppt pictures appear one by one

How to convert pdf documents into jpg images with Foxit PDF Reader - How to convert pdf documents into jpg images with Foxit PDF Reader How to convert pdf documents into jpg images with Foxit PDF Reader - How to convert pdf documents into jpg images with Foxit PDF Reader Mar 04, 2024 pm 05:49 PM

How to convert pdf documents into jpg images with Foxit PDF Reader - How to convert pdf documents into jpg images with Foxit PDF Reader

How to use JavaScript to implement the drag and zoom function of images? How to use JavaScript to implement the drag and zoom function of images? Oct 27, 2023 am 09:39 AM

How to use JavaScript to implement the drag and zoom function of images?

How to use HTML, CSS and jQuery to implement advanced functions of image merging and display How to use HTML, CSS and jQuery to implement advanced functions of image merging and display Oct 27, 2023 pm 04:36 PM

How to use HTML, CSS and jQuery to implement advanced functions of image merging and display

How to arrange two pictures side by side in wps document How to arrange two pictures side by side in wps document Mar 20, 2024 pm 04:00 PM

How to arrange two pictures side by side in wps document

See all articles