1.jsp页面直接引入
<script type="text/javascript" src="js/jquery/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery/ajaxfileupload.js"></script>
<script type="text/javascript" src="js/jquery/jquery.json-2.4.js"></script>
<script type="text/javascript">
//定时器对象
var uploadProcessTimer = null;
function ajaxFileUpload()
{
$.ajaxFileUpload
({
url:'/upload/mvc/upload.do',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
data:{name: $('#name').val()},
success: function (data, status)
{
//清除定时器
if(uploadProcessTimer) {
window.clearInterval(uploadProcessTimer);
}
$('#loading').hide();
var message = data['message'];
var code = data['code'];
if(code != 200) {
$('#fileUploadProcess').html('0%');
}
if(message)
{
alert(data.message);
}
},
error: function (data, status, e)
{
//清除定时器
if(uploadProcessTimer) {
window.clearInterval(uploadProcessTimer);
}
$('#loading').hide();
//这里处理的是网络异常,返回参数解析异常,DOM操作异常
alert("上传发生异常");
}
})
return false;
}
</script>
附件:<input id="fileToUpload", name="file" type="file" class="input"> <br/>
<br><br>
<input type="button" οnclick="return ajaxFileUpload();" value="上传"><br/>
java:
@RequestMapping(value = "upload", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> fileUpload(
@RequestParam("file") CommonsMultipartFile file,
HttpSession session, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// 清除上次上传进度信息
String saveDirectoryPath = Constants.UPLOAD_PLATFORM + "/" + uploadFolderName;
File saveDirectory = new File(saveDirectoryPath);
if (!saveDirectory.exists()) {
saveDirectory.mkdir();
}
// 判断文件是否存在
if (!file.isEmpty()) {
String fileName = file.getOriginalFilename();
file.transferTo(new File(saveDirectory, fileName));
}
return State.OK.toMap();
}
public enum State {
OK(200, "上传成功"),
ERROR(500, "上传失败"),
OVER_FILE_LIMIT(501, "超过上传大小限制"),
NO_SUPPORT_EXTENSION(502, "不支持的扩展名");
private int code;
private String message;
private State(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public Map<String, Object> toMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", this.code);
map.put("message", this.message);
return map;
}
}