使用Jersery发送图片到服务器

导包

在这里插入图片描述

demo

	public static void main(String[] args) throws IOException {
	
		//实例化Jersey
		Client client = new Client();
		
		//本地路径
		String path = "E:\\我的相册\\image2\\(1).jpg";
		
		//另一台服务器请求路径
		String url = "http://localhost:8088/web-image/image/qqqq.jpg";
		
		//设置请求路径
		WebResource resource = client.resource(url);
		
		//读图片到内存中
		byte[] readFileToByteArray = FileUtils.readFileToByteArray(new File(path));
		
		//发送开始PUT
		resource.put(String.class, readFileToByteArray); 
		
	}

ResponseUtils


	public static void reader(HttpServletResponse response,String content,String text){
		response.setContentType(content);
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void responseJson(HttpServletResponse response,String text){
		reader(response, "application/json;charset=utf-8", text);
	}
	
	public static void responseXml(HttpServletResponse response,String text){
		reader(response, "application/xml;charset=utf-8", text);
	}

上传图片核心代码

@RequestMapping("/upload/uploadPic.do")
	public void uploadPic(@RequestParam(required = false) MultipartFile pic, HttpServletResponse response)
			throws IOException {
		// 获取文件扩展名
		String ext = FilenameUtils.getExtension(pic.getOriginalFilename());
		// 生成路径地址
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String format = dateFormat.format(new Date());
		// 实例化Jersey
		Client client = new Client();
		// 保存数据库路径
		Random r = new Random();
		for (int i = 0; i < 3; i++) {
			format += r.nextInt(9);
		}
		String path = "upload/" + format + "." + ext;
		// 另一台服务器请求路径
		String url = "http://localhost:8088/web-image/" + path;
		// 设置请求路径
		WebResource resource = client.resource(url);
		// 读图片到内存中	
		// 发送开始PUT
		resource.put(String.class, pic.getBytes());
		JSONObject json = new JSONObject();
		json.put("url", url);
		json.put("path", path);
		ResponseUtils.responseJson(response, json.toString());
	}

前台页面代码

<script type="text/javascript">
		function uploadPic() {
			var options = {
				url : "/upload/uploadPic.do",
				dataType : "json",
				type : "post",
				success : function(data) {
					$("#allImgUrl").attr("src",data.url);
					$("#path").val(data.path);
				}
			}
			$("#jvForm").ajaxSubmit(options);
		}
	</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值