微信小程序wx.upload上传图片后台java

前台代码:

bindPhoto(e) {
var that = this;
wx.chooseImage({
count: 1,
sizeType: [ 'original', 'compressed'], // 指定原图或者压缩图
sourceType: [ 'album', 'camera'], // 指定图片来源
success: function (res) {
var tempFilePaths = res.tempFilePaths;
wx.uploadFile({
url: 'http://192.168.31.111:8007/goods/wx_upload.do',
filePath: tempFilePaths[ 0],
name: 'file',
header: { "Content-Type": "multipart/form-data" },
formData:{
'session_token': token
},
success: function(res){
var cur_data = res.data;
console.log(cur_data.fileName);
},
fail: function (res) {
console.log( '上传失败');
}
})
}
})
},

后台代码
/*微信小程序上传图片测试*/
@RequestMapping("wx_upload.do")
public void wx_upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding("utf-8");  //设置编码
    //获得磁盘文件条目工厂
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    String fileId = null;
    String json = "{\"success\":false,\"fileName\":\"" + fileId + "\"}";
    String pathUrl = FSDefaultMgr.E_DEFAULT.getDefaultUploadPathUrl();//获取图片服务器路径
    InputStream inStream = null;
    try {
        //可以上传多个文件
        List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
        for(FileItem item : list){
            //获取表单的属性名字
            String name = item.getFieldName();
            //如果获取的 表单信息是普通的 文本 信息
            if(item.isFormField()){
                //获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
                String value = item.getString() ;
                request.setAttribute(name, value);
            }else {
                //获取路径名
                String filename = item.getName();
                request.setAttribute(name, filename);
                inStream = item.getInputStream() ;
            }
        }
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] bytes = swapStream.toByteArray();
        fileId = FastDFSClient.uploadFile(bytes, "20161545454.png", null);
        if (fileId != null) {
            json = "{\"success\":true,\"pathUrl\":\"" + pathUrl + "\",\"fileName\":\"" + fileId + "\"}";
        }
        response.getWriter().write(json);
        response.getWriter().flush();
        response.getWriter().close();
    }catch (Exception e) {
        e.printStackTrace();
    }
}
注意事项:(http://blog.csdn.net/lwphk/article/details/43015829)

猜你喜欢

转载自blog.csdn.net/Dream_hmh/article/details/78666248
今日推荐