SpringMVC结合ajaxfileupload.js实现异步上传文件
2016-07-18 15:07
1006 查看
相比较提交表单实现文件上传,使用ajaxfileupload.js实现异步上传显得更加灵活。
下载ajaxfileupload.js并在页面中引用,jsp代码:
服务器端代码:
UploadUtil类:
StringUtil的checkDir方法:
param.properties的上传路径配置:
![](https://oscdn.geek-share.com/Uploads/Images/Content/201909/10/321c35037a7f9ae14de54ae8a3edc7f4)
至此完成ajaxfileupload.js的异步上传
下载ajaxfileupload.js并在页面中引用,jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="${ctx }/static/scripts/ajaxfileupload.js"></script> <style> .filebtn{ opacity:0; filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0); /* IE6/IE7/8 */ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /* IE8 */ width:70px; position:absolute; top:0; left:0 } </style> </head> <body> <div> <!--这里实现了兼容ie8下的文件上传,同时保持设计的样式--> <span style="position:relative"> <input type="button" class="table-btn" value="选择文件" /> <input type="file" name='file' id='file' class="filebtn"/> </span> <input id="upfile" type="button" value="上传" class="table-btn" onclick="uploadPlanPic()" /> </div> </body> <script> //上传文件 function uploadPlanPic() { var filepath=$("#file").val(); if(filepath ==""){ alert("请选择图片进行上传!"); return; } var extStart=filepath.lastIndexOf("."); var ext=filepath.substring(extStart,filepath.length).toUpperCase(); if(ext!='JPG'||ext!='GIF'||ext!='PNG'||ext!='BMP'){ alert('上传图片格式仅限于.jpg .gif .png .bmp'); return; } $.ajaxFileUpload ( { url:'${ctx}/zxlr/ghxx/uploadPlanpicFile', //用于文件上传的服务器端请求地址 secureuri: false, //一般设置为false fileElementId: 'file', //文件上传控件的id属性 dataType: 'json', //返回值类型 一般设置为json success: function (data, status) //服务器成功响应处理函数 { if (typeof (data.result) != 'undefined') { if(data.result == "success") { alert("文件上传成功!"); }else{ if(data.msg == "error1"){ alert("上传失败,请上传小于10M的文件!"); }else if(data.msg == "error3"){ alert("该文件名已经被使用"); }else{ alert("文件上传失败,请重新上传!"); } } } }, error: function (data, status, e)//服务器响应失败处理函数 { alert("文件上传失败,请重新上传!"); } } ) } </script> </html>
服务器端代码:
@RequestMapping("/ghxx/uploadPlanpicFile") public String uploadContFile(HttpServletRequest request, HttpServletResponse response){ final String message = ""; try { final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; final MultipartFile myfile = multiRequest.getFile("file"); final InputStream stream = myfile.getInputStream(); final InputStream stream2 = myfile.getInputStream(); final String vm = UploadUtil.validateImg(myfile, stream); if (!"success".equals(vm)) { UploadUtil.writeToPage(vm, response); return null; } final String filename = myfile.getOriginalFilename(); //final String newfileName = UploadUtil.getOrderNum() + filename.substring(filename.lastIndexOf('.')); // 这里是物理路径,在实际环境中将配置虚拟路径 final String filePath = UploadUtil.getPropertieValue("param.properties", "uploadPlanpic.path"); StringUtil.checkDir(filePath); File file =new File(filePath +File.separator+ filename); String isExist = UploadUtil.validateExistOrNo(file); if (!"success".equals(isExist)) { UploadUtil.writeToPage(isExist, response); return null; } OutputStream bos = new FileOutputStream(file); int bytesRead = 0; final byte[] buffer = new byte[8192]; while ((bytesRead = stream2.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead);// 将文件写入服务器 } bos.close(); stream2.close(); stream.close(); UploadUtil.writeToPage(UploadUtil.makeJsonResponse(true, filename), response); return null; } catch (final FileNotFoundException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } UploadUtil.writeToPage(UploadUtil.makeJsonResponse(false, message), response); return null; }
UploadUtil类:
package com.jusfoun.estate.util.common; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Properties; import javax.servlet.http.HttpServletResponse; import org.springframework.web.multipart.MultipartFile; /** *上传文件工具类 * @author bukai * */ public class UploadUtil { /** * 拼接json * @param result * @param message * @return */ public static String makeJsonResponse(boolean result, String message) { if (result) { return "{\"result\":\"success\",\"msg\":\"" + message + "\"}"; } return "{\"result\":\"faild\",\"msg\":\"" + message + "\"}"; } /** *ajax打印到前台 * @param content * @param response */ public static void writeToPage(String content, HttpServletResponse response) { response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type", "text/html; charset=UTF-8"); PrintWriter pw = null; try { pw = response.getWriter(); pw.write(content); } catch (final IOException e) { } finally { if (pw != null) { pw.flush(); pw.close(); } } } /** * 获取配置文件 * @param propsName 配置文件名字 * @return */ public static String getPropertieValue(String propsName, String key) { try { InputStream inputStream; final ClassLoader cl = UploadUtil.class.getClassLoader(); if (cl != null) { inputStream = cl.getResourceAsStream(propsName); } else { inputStream = ClassLoader.getSystemResourceAsStream(propsName); } final Properties dbProps = new Proper 4000 ties(); dbProps.load(inputStream); inputStream.close(); String p = dbProps.getProperty(key); return dbProps.getProperty(key); } catch (final Exception e) { // TODO: handle exception } return ""; } /** *验证文件大小 * @param myfile * @param stream * @return */ public static String validateImg(MultipartFile myfile, InputStream stream) { try { final long size = myfile.getSize(); if (size > (1024 * 1023 * 10)) { return UploadUtil.makeJsonResponse(false, "error1"); } } catch (final Exception e) { e.printStackTrace(); } return "success"; } /** * 验证文件是否已经存在 * @param file * @return */ public static String validateExistOrNo(File file){ if(file.exists()){ return UploadUtil.makeJsonResponse(false, "error3"); } return "success"; } /** *判断字符串 * @param s * @return */ public static boolean isNull(String s) { if ((s == null) || s.equals("")) { return true; } else { return false; } } }
StringUtil的checkDir方法:
/** * 检查文件夹是否存在, 不存在则创建 * * @param path */ public static void checkDir(String path) { File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } }
param.properties的上传路径配置:
uploadPlanpic.path=D\://PlanpicFiles
至此完成ajaxfileupload.js的异步上传
相关文章推荐
- 命令行小技巧:读取文件的不同方式
- IE:临时文件保存法
- 文件的读出 编辑 管理
- 文件遍历排序函数
- 在线用表单建立文件夹
- VB获取文件大小的方法
- 文件、目录,文本文件等多种操作类
- 处理驱动器和文件夹
- 用vbs删除某些类型文件和磁盘空间报告的脚本
- Ruby实现批量对文件增加前缀代码分享
- C#获取文件夹及文件的大小与占用空间的方法
- delphi制作wav文件的方法
- PowerShell实现查询打开某个文件的默认应用程序
- bat 文件 学习使用指南
- IIS配置文件隐患
- Shell中删除某些文件外所有文件的3个方法
- winform实现拖动文件到窗体上的方法
- redis中修改配置文件中的端口号 密码方法
- 同步文件备份工具 Super Flexible File Synchronizer Pro v4
- C#获取文件创建时间的方法