微信小程序java开发图片上传 ssm框架

微信小程序图片上传与pc端图片上传是不同的,话不多说直接上代码:(复制粘贴可用)

微信小程序端:

chooseImage(){  
  wx.chooseImage({  
    success: function (res) {  
      var tempFilePaths = res.tempFilePaths  
      wx.uploadFile({  
        url: 'http://127.0.0.1:8888/pesss/weChat/uploadImage.do',   
        filePath: tempFilePaths[0],  
        name: 'file',  
        formData: {  
          'user': 'test'  
        },  
        success: function (res) {  
          var data = res.data  
          //do something  
        },fail:function(err){  
          console.log(err)  
        }  
      })  
    }  
  })  
}  

后端代码

/**
	 * 直播间图片上传
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "/uploadImage", method = { RequestMethod.POST,RequestMethod.GET})  
    public void weChatImage(HttpServletRequest request, HttpServletResponse response) throws IOException {  
        System.out.println("进入get方法!");  
        
        MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;  
        MultipartFile multipartFile =  req.getFile("uploadfile_ant"); //对应前端页面的name值
  
        String path=request.getSession().getServletContext().getRealPath("/image/");
            File dir = new File(path);  
            if (!dir.exists()) {  
                dir.mkdir();  
            }  
            //生成一个新的文件名fileName
            String n=UUID.randomUUID().toString().substring(0, 11);
            String picName =n + "."+ "jpg";
            String d="/image/"+picName;
            File file  =  new File(path,picName);  
            multipartFile.transferTo(file);  
            //返回图片名
	        PrintWriter printWriter = response.getWriter();
	        response.setContentType("application/json");
	        response.setCharacterEncoding("utf-8");
	        HashMap<String, Object> res = new HashMap<String, Object>();
	        res.put("success", true);
	        printWriter.write(JSON.toJSONString(d));
	        printWriter.flush();        
    }  
	

注意:1.加粗的地方要与前端对应上

          2.返回文件路径时:用阿里巴巴的jsonobject与net.sf.json.JSONObject, 返回会报错,所以只能用response

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值