使用jesey实现跨服务器文件上传,再通过ajax把绝对路径和相对路径返回前端,通过绝对路径实现回显,把相对路径通过表的提交存入数据库。
jsp(测试代码):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="Content-Type"; content="multipart/form-data; charset=utf-8"/>
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery/jquery.form.js"></script>
<script type="text/javascript">
function fileOnchage(){
var option = {
type:"post",
data:{pictureFile:'pictureFile'},
dataType:"json",
url:"${pageContext.request.contextPath }/rest/AdminController/uploadPic",
success:function(data){
var path=data['realPath'];
$("#picImg").append("<img id='myImg' src='"+path+"'/>");
}
}
$("#fileForm").ajaxSubmit(option);
}
</script>
</head>
<body>
<form id="fileForm" method="post" enctype="multipart/form-data">
<div id="picImg"></div>
<input type="file" name="pictureFile" id="pictureFile" value="请选择" onchange="fileOnchage()"/>
</form>
</body>
</html>
Controller代码:
@RequestMapping(value = "/uploadPic",method = RequestMethod.POST)
public @ResponseBody JSONObject uploadPic(HttpServletRequest request, MultipartFile pictureFile) throws IOException {
// 获得文件上传流
byte[] fileBytes = pictureFile.getBytes();
String newFilename = "";
//使用UUID创建一个文件在服务器的随机名字,以免出现名字重复
newFilename = ImageUtils.newname(request, pictureFile);
// 创建jesey服务器,进行跨服务器上传
Client client = Client.create();
// 将文件关联到远程服务器
// 这里的Commons.pic="http://192.172.x.x:8089/Filesevice",也就是图片服务器
WebResource resource = client.resource(Commons.pic + "/upload/" + newFilename);
// 上传到服务器
resource.put(String.class, fileBytes);
// 图片需要回显:绝对路径
String realPath = Commons.pic + "/upload/" + newFilename;
// 数据库需要保存:相对路径
String relativePath = "/upload/" + newFilename;
String result = "{\"realPath\":\"" + realPath + "\",\"relativePath\":\"" + relativePath + "\"}";
// 将相对路径写回(json格式)
JSONObject jsonObject = new JSONObject();
// 将图片上传到本地
jsonObject.put("realPath", realPath);
jsonObject.put("relativePath", relativePath);
return jsonObject;
}
utils代码:
public static String newname(HttpServletRequest request, MultipartFile pictureFile) throws IOException {
String imgname= null;//装配后的图片地址
//上传图片
if(pictureFile!=null&&!pictureFile.isEmpty()){
// 使用UUID给图片重命名,并去掉四个“-”
String name = UUID.randomUUID().toString().replaceAll("-", "");
// 获取文件的扩展名(img\png\gif)-----FilenameUtils工具类
String ext = FilenameUtils.getExtension(pictureFile
.getOriginalFilename());
// 装配图片地址
imgname =name + "." + ext;
}
return imgname;
}