导包
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>