工作中用到了文件上传,因为各种原因只能通过异步来实现。参考的异步上传插件地址:
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
代码开发部分:
jsp页面:
<td class="sw_list border_r_none" align="center"><input id="fileToUpload" type="file" size="45" name="fileToUpload" class="sw_input_04" /> <a
id="buttonUpload" onclick="return ajaxFileUpload();" class="sw_button sw_btn03" role="button">上传</a></td>
javascript脚本:
function ajaxFileUpload() {
$.ajaxFileUpload({
url : path + '/publicity/upload',
secureuri : false,
fileElementId : 'fileToUpload',
dataType : 'json',
data : {
name : 'logan',
id : 'id'
},
success : function(data, status) {
var showfile = $('#showfile');
var str = '<tr class="sw_tr_name"><td class="sw_list" align="center"> '
+ '<input name="doc_checkbox" type="checkbox" />'
+ '<input name="realfilename" size="500" style="display:none;" type="text" value='+data.realfilename+' ></td>'
+ '<td class="sw_list border_r_none" align="center">'
+ '<input type="text" size="45" name="deluploadfile" class="sw_input_04" value='+data.filename+' /> '
+ ' <a onclick="delfile(\''+data.filename+'\');" class="sw_button sw_btn03" role="button">删除</a></td></tr>';
showfile.after(str);
},
error : function(data, status, e) {
$.jBox.tip(e);
}
});
return false;
}
java后台文件上传的处理:
public static String replaceBlank(String str) {
String dest = "";
if (str!=null) {
Pattern p = Pattern.compile("\\s*|t|r|n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
@RequestMapping("upload")
public void upload(MultipartFile fileToUpload, HttpServletRequest request, HttpServletResponse response) {
String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/doc/");
String fileName = fileToUpload.getOriginalFilename();
fileName=replaceBlank(fileName);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String newfileName = fileName.substring(0, fileName.lastIndexOf(".")).concat(sdf.format(new Date())).concat(fileName.substring(fileName.lastIndexOf("."), fileName.length()));
System.out.println(path);
File targetFile = new File(path, newfileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
fileToUpload.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
try {
response.setContentType("text/html;charset=utf-8");
// json格式数据{"城市":"北京","面积":16800,"人口":1600}
String res = "{ msg:'上传成功', filename:'" + fileName + "',realfilename:'" + newfileName + "'}";
response.getWriter().print(res);
} catch (Exception e) {
try {
} catch (Exception e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}