用了半天时间才脱坑,用的struts2框架,因此纠结了很长很长时间。。。。因为网上找不到struts2框架接收小程序所传图片的教程,自己搞了一个,亲测好用,废话不说粘代码。。。。
package com.jeanLeung.gogo.controller.auth;
import com.jeanLeung.gogo.model.AdviseUser;
import com.jeanLeung.gogo.service.AdviseUserService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.StrutsUploadedFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
public class Sign extends ActionSupport {
private HttpServletRequest request = ServletActionContext.getRequest();
private StrutsUploadedFile userInfo;
@Override
public String execute() throws IOException {
System.out.println("userInfo:" + userInfo);
System.out.println(userInfo.isFile());
String realPath = "F:/image";
try {
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(realPath,idCard + ".jpg");
InputStream inputStream = new FileInputStream(userInfo.getContent());
OutputStream outputStream = new FileOutputStream(file);
byte[] b=new byte[1024];
//一边读一边写
while(inputStream.read(b)!=-1) {
outputStream.write(b);
}
//关闭流
inputStream.close();
outputStream.close();
System.out.println("文件copy成功");
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
return NONE;
}
public StrutsUploadedFile getUserInfo() {
return userInfo;
}
public void setUserInfo(StrutsUploadedFile userInfo) {
this.userInfo = userInfo;
}
}
思想其实很简单,就是用private StrutsUploadedFile userInfo;来接收微信小程序传来的图片,哦对了,我的微信小程序前端代码:
wx.uploadFile({
url: `${app.globalData.subDomain}/Frank/Auth/sign?id=${+index}`, // +index 把index 转换成number格式
filePath: filePaths[index],
name: 'userInfo',
header: {
'content-type': 'multipart/form-data'
}, // 设置请求的 header
formData: info, // HTTP 请求中其他额外的 form data
success: function (res) {
console.log('信息上传成功', res)
wx.showToast({
title: '信息上传成功!',
icon: 'success',
duration: 0
})
wx.navigateTo({
url: "/pages/payment/payment"
})
}
})
可以看出我微信小程序上传的那张图片的名字是userInfo,所以我们定义变量StrutsUploadedFile userInfo以及该变量的set方法来让struts2框架帮我们自动设置进去,然后就简单了,吧userInfo转成File,再用输入流输出流写到事先定义好的文件里,转为图片。