微信小程序按序上传多图片(小程序端+后端Java代码)

  • 小程序端使用wx.uploadFile()上传图片,后端Java接收并返回结果;
  • wx.uploadFile().complete()接收结果,并决定是否调用wx.uploadFile()上传下一张图片;
  • 以上方式有别于for循环调用wx.uploadFile(),for循环相当于一次性发送所有图片,后端接收无规则,若其中一张图片接收失败,会出现数据不一致的情况;
  • 故本人采用按序上传的方式,根据前一次的上传结果决定是否进行下一次上传;
  • Java新手初出茅庐,有不足的地方请指正。

前端(xxx.js)

ChooseImage() {
    var that = this
    wx.chooseImage({
        count: 3, //默认9
        sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
        sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
        success: (res) => {
            var imgList = that.data.imgList
            if (imgList.length != 0) {
                that.setData({
                imgList: imgList.concat(res.tempFilePaths)
                })
            } else {
                that.setData({
                imgList: res.tempFilePaths
                })
            }
            console.log(that.data.imgList)
        },
       fail: function() {
            //fail
       },
       complete: function() {
            //complete
       }
    })
  },

uploadImage: function(data){
    var that = this
    var imageNum = that.data.imgList.length
    var i = data.i ? data.i : 0
    wx.uploadFile({
        url: 'http://localhost:8080/...',       //上传图片的网路请求地址
        filePath: that.data.imgList[i],
        name: 'file',
        formData: { 
            "imageType": 'XXXImage',
            "id": data.id,
            "imageId": i,
            "imageNum": imageNum
        },
        success: function (res) {
            //success
        },
        fail: function (res) {
            //fail
        },
        complete: function (res) {
            i++;
            var json = JSON.parse(res.data)
            var json2 = JSON.parse(json)
            if (i == imageNum && json2['result'] == "success") {   //当图片传完时,停止调用
                console.log("全部上传完成"+i+"张")
                
                //返回上一页,并传参给onLoad
                var pages = getCurrentPages()   //获取页面栈
                var beforePage = pages[pages.length - 2]    //上一页
                var options = {title: that.data.title}
                beforePage.onLoad(options)
                wx.navigateBack({
                    delta: 1  //返回上一页
                })
                
            } else if(json2['result'] == "pass") {  //若图片还没有传完,则继续调用函数      
                console.log("上传完成第"+i+"张")
                data.i = i
                that.uploadImage(data)
            } else if(json2['result'] == "error") {
              that.setData({
                modal: {
                  isShow: true,
                  warnInfo: '提交失败!'
                }
              })
            }
        }
    })
}

后端(SSH框架)

package com.action;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.service.XXXService;
import com.alibaba.fastjson.JSONObject;
import com.util.CommonUtils;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {
    //提交过来的文件
    private File file;
    //提交过来的file的名字
    private String fileFileName;
    //提交过来的file的类型
    private String fileContentType;
    private JSONObject jsonResult;
    private XXXService xxxService;  
    public File getFile() {
        return file;
    }
    public void setFile(File file) {
        this.file = file;
    }
    public String getFileFileName() {
        return fileFileName;
    }
    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }
    public String getFileContentType() {
        return fileContentType;
    }
    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }
    public JSONObject getJsonResult() {
        return jsonResult;
    }
    public void setJsonResult(JSONObject jsonResult) {
        this.jsonResult = jsonResult;
    }
    
    public String uploadImage() {
        try {
            String imageName = CommonUtils.getAndSaveImageUpload(file, fileFileName);       
            HttpServletRequest request = ServletActionContext.getRequest();
            String imageType = request.getParameter("imageType");
            String id = request.getParameter("id");
            Integer imageNum = Integer.parseInt(request.getParameter("imageNum"));
            Integer imageId = Integer.parseInt(request.getParameter("imageId"));                
            if("XXXImage".equals(imageType)) {              
                jsonResult= this.xxxService.updateXXXImage(id, imageId, imageName, imageNum);               
            }
        }catch (Exception e) {
            jsonResult= CommonUtils.getException(e);
        }       
        return SUCCESS;
    }
}
package com.service.impl;

import java.util.List;
import com.dao.XXXDao;
import com.service.XXXService;
import com.util.CommonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class XXXServiceImpl implements XXXService {
    private JSONObject jsonResult;
    private XXXDao xxxDao;
    public void setXXXDao(XXXDao xxxDao) {
        this.xxxDao = xxxDao;
    }
    public String updateXXXImage(String id, Integer imageId, String imageName, Integer imageNum) {
        try {
            List<String> imageList = this.xxx.findImageById(id);    //根据主键id,获取保存的图片List
            JSONObject imageJSON = CommonUtils.packImageJSON(imageList, imageId, imageName);    //封装图片JSON
            if(null != imageJSON) {
                Boolean isPass = this.xxx.updateXXXImage(imageJSON.toJSONString(), id);     //更新图片List
                jsonResult= CommonUtils.packSaveImageResult(isPass, imageJSON.getInteger("count"), imageNum);       //返回前端结果JSON字符串
            }else {
                jsonResult= CommonUtils.packNullResult();
            }
        }catch (Exception e) {
            jsonResult= CommonUtils.getException(e);
        }   
        return jsonResult;
    }
}
package com.dao.impl;

import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.dao.XXXDao;

public class XXXDaoImpl implements XXXDao {
    
    //提供Hibernate模板
    private HibernateTemplate hibernateTemplate;
    
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
    
    public Boolean updateXXXImage(String image, String id) {
        Boolean isPass = false; 
        try {
            String queryString = "update XXX set image = ? where id = ?";
            Integer num = this.hibernateTemplate.bulkUpdate(queryString, new Object[]{image, id});
            if(num > 0) {
                isPass = true;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        
        return isPass;
    }
}
package com.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.model.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.coobird.thumbnailator.Thumbnails;

public class CommonUtils {

    //获取图片并保存
    public static String getAndSaveImageUpload(File file, String fileFileName) {    
        String ImageName = null;
        try {
            HttpServletRequest request = ServletActionContext.getRequest();
            request.setCharacterEncoding("UTF-8");      
            String imageType = request.getParameter("imageType");       
            //文件输入流
            InputStream is = new FileInputStream(file);     
            //设置文件保存的目录
            String uploadPath = "D:\\Upload\\"+imageType;       
            //格式化时间戳
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
            String nowTime = sdf.format(new Date().getTime());      
            //随机生成10位uuid
            UUID uuid = UUID.randomUUID();
            String uuidStr = uuid.toString().substring(0,10); 
            //取得图片的格式后缀
            String ImageLastName = fileFileName.substring(fileFileName.lastIndexOf("."));
            //拼接:名字+时间戳+后缀
            ImageName = uuidStr + "_" + nowTime + ImageLastName;        
            File dir = new File(uploadPath);
            //如果文件目录不存在,创建文件目录
            if (!dir.exists()) {
                dir.mkdir();
                System.out.println("创建文件目录成功:" + uploadPath);
            }       
            //设置目标文件
            File toFile = new File(uploadPath, ImageName);
            
            //以下由两种方式保存图片,二选一
            //一、以上传的图片为标准保存:
            /*OutputStream os = new FileOutputStream(toFile);
             *byte[] buffer = new byte[1024];
             *int length = 0;
             *读取file文件输出到toFile文件中
             *while(-1 != (length = is.read(buffer, 0, buffer.length))) {
             *  os.write(buffer);
             }*/
            //关闭输入流和输出流
            //is.close();
            //os.close();
            
            //二、对图片进行压缩,使用Thumbnails工具类
            //Thumbnails.of(is).scale(0.5).toFile(toFile);
            //关闭输入流和输出流
            //is.close();       
        } catch (Exception e) {
            e.printStackTrace();
        }   
        return ImageName;
    }

    //图片JSON封装
    public static JSONObject packImageJSON(List<String> imageList, Integer imageId, String imageName) {
        JSONObject imageJSON = null;
        try {
            if(null != imageList) {
                StringBuffer sb = new StringBuffer();
                Integer count = 1;
                if(null != imageList.get(0)) {
                    JSONObject jsonObject = JSON.parseObject(imageList.get(0));
                    String data = jsonObject.getString("data");
                    String images = data.substring(1, data.length() - 1);               
                    count = jsonObject.getInteger("count") + 1;             
                    sb.append("{\"count\":"+count+",");
                    sb.append("\"data\":["+images+",{");                
                }else {             
                    sb.append("{\"count\":"+count+",");
                    sb.append("\"data\":[{");           
                }
                sb.append("\"id\":"+imageId+",");
                sb.append("\"type\":\"image\",");
                sb.append("\"imageName\":\""+imageName+"\"");
                sb.append("}]");
                sb.append("}");
                imageJSON = JSON.parseObject(sb.toString());
            }else {
                System.out.println("CommonUtils.packImageJSON()中imagelist为null!");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return imageJSON;
    }

    //返回保存图片结果
    public static JSONObject packSaveImageResult(Boolean isPass, Integer count, Integer imageNum) {
        Result result = new Result();  //两个属性:result、message
        String resultMsg = "error";
        String message = "保存图片失败!";
        if(isPass) {
            resultMsg = "pass";
            message = "保存第"+count+"张图片成功!";
            if(count.equals(imageNum)) {
                resultMsg = "success";
                message = "全部"+count+"张图片保存成功!";
            }
        }else {
            message = "保存第"+count+"张图片异常!";
        }   
        result.setResult(resultMsg);
        result.setMessage(message);
        JSONObject jsonResult = (JSONObject) JSON.toJSON(result);
        return jsonResult;
    }
    
    //异常封装
    public static JSONObject getException(Exception e) {
        Result result = new Result();   //两个属性:result、message
        result.setResult("error");
        result.setMessage("出现异常!\n请截图并反馈管理员!\n"+e.getClass());
        JSONObject jsonResult = (JSONObject) JSON.toJSON(result);
        return jsonResult;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354