微信小程序上传图片到java后台

微信小程序

wxml

wxss

.big-logos {
float: left;
margin-top: 10rpx;
margin-bottom: 10rpx;
width: 100%;
height: 200rpx;
border: 1px solid #ccc;
}
.big-logos .big-logos_img {
float: left;
width: 100%;
height: 200rpx;
}
.big-logos .big-logos_img image {
float: left;
width: 250rpx;
height: 200rpx;
}
.big-logos .logoinfo {
float: left;
width: 250rpx;
height: 200rpx;
margin-top: -196rpx;
}
.big-logos .logoinfo image {
float: left;
width: 250rpx;
height: 200rpx;
}

js

var adds = {};
Page({
  data: {
    img_arr: [],
    formdata: '',
  },
  formSubmit: function (e) {
    var id = e.target.id
    adds = e.detail.value;
    this.upload()
  },

  upload: function () {
    var that = this
    for (var i = 0; i < this.data.img_arr.length; i++) {
      wx.uploadFile({
url: 'http://localhost:8080/asp/servlet/picture',
filePath: that.data.img_arr[i], header: { 'content-type': 'application/x-www-form-urlencoded' }, name: 'content', formData: adds, success: function (res) { console.log(res) console.log("成功") if (res) { wx.showToast({ title: '已提交成功!', duration: 3000 }); } } }) } this.setData({ formdata: '' }) }, //选择图片上传到小程序 upimg: function () { var that = this; if (this.data.img_arr.length < 3) { wx.chooseImage({ sizeType: ['original', 'compressed'], success: function (res) { that.setData({ img_arr: that.data.img_arr.concat(res.tempFilePaths) }) console.log(res.tempFilePaths) console.log("上传成功!!!!") } }) } else { wx.showToast({ title: '最多上传三张图片', icon: 'loading', duration: 3000 }); } }, });

java后台

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

public class picktrue_zxt extends HttpServlet {
    private String path="D:\\JAVA\\uploader\\file\\";
    private File file = null;

    {
        file = new File(path);

        if(!file.exists()){
            file.mkdir();
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取文件需要上传到的路径

        request.setCharacterEncoding("utf-8");  //设置编码
        //获得磁盘文件条目工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //如果没以下两行设置的话,上传大的文件会占用很多内存,
        //设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
        /**
         * 原理: 它是先存到暂时存储室,然后再真正写到对应目录的硬盘上,
         * 按理来说当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的
         * 然后再将其真正写到对应目录的硬盘上
         */
        factory.setRepository(file);
        //设置缓存的大小,当上传文件的容量超过该缓存时,直接放到暂时存储室
        factory.setSizeThreshold(1024 * 1024);
        //高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List list = upload.parseRequest(request);
            FileItem picture = null;
            for (FileItem item : list) {
                //获取表单的属性名字
                String name = item.getFieldName();
            	//System.out.println(name); 
                //如果获取的表单信息是普通的 文本 信息
                if (item.isFormField()) {
                    //获取用户具体输入的字符串
                    String value = item.getString();
                    request.setAttribute(name, value);
                } else {
                    picture = item;
                }
            }
            String fileName = request.getAttributeNames() + ".jpg";
            String destPath = path + fileName;

            //真正写到磁盘上
            File file = new File(destPath);
            OutputStream out = new FileOutputStream(file);
            InputStream in = picture.getInputStream();
            int length = 0;
            byte[] buf = new byte[1024];
            // in.read(buf) 每次读到的数据存放在buf 数组中
            while ((length = in.read(buf)) != -1) {
                //在buf数组中取出数据写到(输出流)磁盘上
                out.write(buf, 0, length);
            }
            in.close();
            out.close();
        } catch (FileUploadException e1) {
        } catch (Exception e) {

            System.out.println(e);
        }

System.out.println("成功上传");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

java中需要的包可以在这里下载-------MAVEN

参考网上代码,终于是实现了微信小程序上传图片到后台,但是有点bug,上传到本地的图片名真的是,不会java真烦人......

微信小程序上传图片到java后台_第1张图片




你可能感兴趣的:(学习笔记)