- 小程序端使用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;
}
}