spring MVC 异步文件上传

工作中用到了文件上传,因为各种原因只能通过异步来实现。参考的异步上传插件地址:

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();
 }
 }


转载于:https://my.oschina.net/kt431128/blog/313811

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值