Java实现文件上传
最近自己在做一个小系统玩的时候涉及到了文件的上传,于是在网上找到Java上传文件的方案,最后确定使用common-fileupload实现上传操作。
?
需求说明用户添加页面有一个“上传”按钮,点击按钮弹出上传界面,上传完成后关闭上传界面。
?
所需Jar包commons.fileupload-1.2.0.jar、commons.logging-1.1.1.jar、commons.beanutils-1.8.0.jar、commons.collections-3.2.0.jar、commons.io-1.4.0.jar、commons.lang-2.1.0.jar
?
实现效果

?
?
?代码实现首先编写核心代码,Javascript打开上传页面,并且从上传页获取返回参数,最后数据返回给回调函数callback:?
?文件上传的JSP代码,需要注意的是在head标签内添加<base target="_self">以防止页面跳转时弹出新窗口,用户选择指定文件,点击上传时就提交表单访问指定后台代码
?
?CommonController目前有两个方法,一个是跳转到上传页面的方法,一个是执行上传操作的方法doFileUpload,上传方法运行的大概逻辑是:首先获取页面的请求参数,fileType用于限制上传文件格式,
maxSize用于限制上传文件最大值,随后创建上传目录上传即可。
?
public class CommonController extends BaseController {Log log = LogFactory.getLog(CommonController.class);Properties fileUploadPro = null;public CommonController(){fileUploadPro = PropertiesUtil.getPropertiesByClass("fileupload.properties");}@Overridepublic ModeAndView init(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {return null;}/** * 跳转到文件上传页 * @param request * @param response * @return * @throws ServletException * @throws IOException */public ModeAndView goFileUpload(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {String functionId = request.getParameter("functionId");String fileType = request.getParameter("fileType");String maxSize = request.getParameter("maxSize");ModeAndView mav = new ModeAndView("/WEB-INF/jsp/common/fileUpload.jsp");if(functionId!=null && !"".equals(functionId.trim())){mav.addObject("functionId", functionId);}if(fileType!=null && !"".equals(fileType.trim())){mav.addObject("fileType", fileType);}if(maxSize!=null && !"".equals(maxSize.trim())){mav.addObject("maxSize", maxSize);}return mav;}/** * 上传文件 * @param request * @param response * @return * @throws ServletException * @throws IOException */@SuppressWarnings("unchecked")public ModeAndView doFileUpload(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {//获取并解析文件类型和支持最大值String functionId = request.getParameter("functionId");String fileType = request.getParameter("fileType");String maxSize = request.getParameter("maxSize");//临时目录名String tempPath = fileUploadPro.getProperty("tempPath");//真实目录名String filePath = fileUploadPro.getProperty("filePath");FileUtil.createFolder(tempPath);FileUtil.createFolder(filePath);DiskFileItemFactory factory = new DiskFileItemFactory();//最大缓存factory.setSizeThreshold(5*1024);//设置临时文件目录factory.setRepository(new File(tempPath));ServletFileUpload upload = new ServletFileUpload(factory);if(maxSize!=null && !"".equals(maxSize.trim())){//文件最大上限upload.setSizeMax(Integer.valueOf(maxSize)*1024*1024);}try {//获取所有文件列表List<FileItem> items = upload.parseRequest(request);for (FileItem item : items) {if(!item.isFormField()){//文件名String fileName = item.getName();//检查文件后缀格式String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();if(fileType!=null && !"".equals(fileType.trim())){boolean isRealType = false;String[] arrType = fileType.split(",");for (String str : arrType) {if(fileEnd.equals(str.toLowerCase())){isRealType = true;break;}}if(!isRealType){//提示错误信息:文件格式不正确super.printJsMsgBack(response, "文件格式不正确!");return null;}}//创建文件唯一名称String uuid = UUID.randomUUID().toString();//真实上传路径StringBuffer sbRealPath = new StringBuffer();sbRealPath.append(filePath).append(uuid).append(".").append(fileEnd);//写入文件File file = new File(sbRealPath.toString());item.write(file);//上传成功,向父窗体返回数据:真实文件名,虚拟文件名,文件大小StringBuffer sb = new StringBuffer();sb.append("window.returnValue='").append(fileName).append(",").append(uuid).append(".").append(fileEnd).append(",").append(file.length()).append("';");sb.append("window.close();");super.printJsMsg(response, sb.toString());log.info("上传文件成功,JS信息:"+sb.toString());}//end of if}//end of for}catch (Exception e) {//提示错误:比如文件大小super.printJsMsgBack(response, "上传失败,文件大小不能超过"+maxSize+"M!");log.error("上传文件异常!",e);return null;}return null;}}?至此一个文件上传即已实现,而且能够基本满足不同模块的上传通用性,我还留着个functionId参数用于以后针对不同模块上传文件到不同目录。
1 楼 傲雪木瓜露 2012-02-17 支持一下。
如果想要在前端校验文件的大小,然后才能上传应该怎么弄啊 2 楼 白糖_ 2012-02-20 傲雪木瓜露 写道支持一下。
如果想要在前端校验文件的大小,然后才能上传应该怎么弄啊
前端验证大小没做过,可以去网上查看一下用JS是否可以实现:http://hi.baidu.com/bit5566/blog/item/589cb44f8886913faec3ab1e.html