页面代码:
<html>
<!-- 引入相关的js文件,相对路径-->
<script type="text/javascript"src="js/jquery.js"></script>
<script type="text/javascript"src="js/ajaxfileupload.js"></script>
<!-- 执行上传文件操作的函数 -->
<script type="text/javascript">
functionajaxFileUpload(){
$.ajaxFileUpload(
{
url:'update.do?method=uploader',//需要链接到服务器地址
secureuri:false,
fileElementId:'houseMaps',//文件选择框的id属性
dataType:'json',//服务器返回的格式,可以是json, xml
success: function (data,status)//相当于java中try语句块的用法
{
$('#result').html('添加成功');
},
error: function (data, status,e)//相当于java中catch语句块的用法
{
$('#result').html('添加失败');
}
}
);
}
</script>
</head>
<body>
<div>
<input type="file" id="houseMaps"name="houseMaps"/>
<input type="button" value="提交"onclick="ajaxFileUpload()"/>
</div>
<divid="result"></div>
</body>
</html>
java代码 :
@RequestMapping(method=RequestMethod.POST,value="/imgupload")
public@ResponseBody String uploadImg(HttpServletRequest request,@RequestParam("imgFile") MultipartFile imgFile){
String uploadDir= request.getRealPath("/upload");
File dirPath = newFile(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
String uuid =UuidUtil.getUUID();
String oriName =imgFile.getOriginalFilename();
//文件名后缀处理---start---
String _suffix =oriName.substring(oriName.lastIndexOf(".")+1,oriName.length());
//-----end---
//---重新处理文件名start---
String suffix =oriName.substring(oriName.lastIndexOf("."),oriName.length());
StringnewFileName = uuid + suffix;
try {
imgFile.transferTo(new File(uploadDir + "/"+ newFileName));
} catch(IllegalStateException e) {
// TODOAuto-generated catch block
e.printStackTrace();
} catch(IOException e) {
// TODOAuto-generated catch block
e.printStackTrace();
}
//---end---
File file = newFile(uploadDir + "/" + newFileName);
String fileUrl =FtpUtil.ftp2NFS(file, "image", newFileName, "test", "image","42");
dirPath.delete();
JSONObject object = newJSONObject();
if("error".equals(fileUrl)){
object.put("success","false");
}else{
object.put("success","true");
object.put("filePath",PropUtil.getImagePath() + fileUrl);
}
returnJSONObject.fromObject(object).toString();
}