Because the combination of wx.chooseImage and wx.uploadFile is very common, and it is extremely easy to encounter pits; please the author to check whether there is a problem, because I see a bunch of unknown codes under the original text. . .
To upload an avatar, use wx.chooseImage({}) and then use wx.uploadFile({}) in combination.
http://www.wxapp-union.com/portal.php?mod=view&aid=907
http://www.wxapp-union.com/forum.php?mod=viewthread&tid=3454
wx.uploadFile (upload file) related issues
Sample code:
Page({ data: { src: "../../image/photo.png", // Bind the src of the image component // Omitted... }, onLoad: function (options) { //略... }, uploadPhoto() { var that = this; wx.chooseImage({ count: 1, // Default 9 sizeType: ['compressed'], // You can specify whether it is the original image or the compressed image, both have the default sourceType: ['album', 'camera'], // You can specify the source is Album or camera, both have success by default: function (res) { // Return the list of local file paths of the selected photo, tempFilePath can be used as the src attribute of the img tag to display the picture var tempFilePaths = res.tempFilePaths; upload(that, tempFilePaths); } }) } }) function upload(page, path) { wx.showToast({ icon: "loading", title: "Uploading" }), wx.uploadFile({ url: constant.SERVER_URL + "/FileUploadServlet", filePath: path[0], name: 'file', header: { "Content-Type": "multipart/form-data" }, formData: { // The token agreed with the server can generally also be placed in the header 'session_token': wx.getStorageSync('session_token' ) }, success: function (res) { console.log(res); if (res.statusCode != 200) { wx.showModal({ title: 'Tips' , content: 'Upload failed' , showCancel: false }) return; } var data = res.data page.setData({ // Upload successfully modifies the display avatar src: path[0 ] }) }, fail: function (e) { console.log(e); wx.showModal({ title: 'Tips' , content: 'Upload failed' , showCancel: false }) }, complete: function () { wx.hideToast (); //隐藏 Toast } }) }
backend code
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(FileUploadServlet.class);
public FileUploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JsonMessage<Object> message = new JsonMessage<Object>();
EOSResponse eosResponse = null;
String sessionToken = null;
FileItem file = null;
InputStream in = null;
ByteArrayOutputStream swapStream1 = null;
try {
request.setCharacterEncoding("UTF-8");
//1、创建一个DiskFileItemFactory工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//2、创建一个文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
//解决上传文件名的中文乱码
upload.setHeaderEncoding("UTF-8");
// 1. 得到 FileItem 的集合 items
List<FileItem> items = upload.parseRequest(request);
logger.info("items:{}", items.size());
// 2. 遍历 items:
for (FileItem item : items) {
String name = item.getFieldName();
logger.info("fieldName:{}", name);
// 若是一个一般的表单域, 打印信息
if (item.isFormField()) {
String value = item.getString("utf-8");
if("session_token".equals(name)){
sessionToken = value;
}
}else {
if("file".equals(name)){
file = item;
}
}
}
//session校验
if(StringUtils.isEmpty(sessionToken)){
message.setStatus(StatusCodeConstant.SESSION_TOKEN_TIME_OUT);
message.setErrorMsg(StatusCodeConstant.SESSION_TOKEN_TIME_OUT_MSG);
}
String userId = RedisUtils.hget(sessionToken,"userId");
logger.info("userId:{}", userId);
if(StringUtils.isEmpty(userId)){
message.setStatus(StatusCodeConstant.SESSION_TOKEN_TIME_OUT);
message.setErrorMsg(StatusCodeConstant.SESSION_TOKEN_TIME_OUT_MSG);
}
//上传文件
if(file == null){
}else{
swapStream1 = new ByteArrayOutputStream();
in = file.getInputStream();
byte[] buff = new byte[1024];
int rc = 0;
while ((rc = in.read(buff)) > 0) {
swapStream1.write(buff, 0, rc);
}
Usr usr = new Usr();
usr.setObjectId(Integer.parseInt(userId));
final byte[] bytes = swapStream1.toByteArray();
eosResponse= ServerProxy.getSharedInstance().saveHeadPortrait(usr, new RequestOperation() {
@Override
public void addValueToRequest(EOSRequest request) {
request.addMedia("head_icon_media", new EOSMediaData(EOSMediaData.MEDIA_TYPE_IMAGE_JPEG, bytes));
}
});
// 请求成功的场合
if (eosResponse.getCode() == 0) {
message.setStatus(ConstantUnit.SUCCESS);
} else {
message.setStatus(String.valueOf(eosResponse.getCode()));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(swapStream1 != null){
swapStream1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(in != null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
PrintWriter out = response.getWriter();
out.write(JSONObject.toJSONString(message));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}