为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

commons-fileupload上传下载

2018-04-15 24页 doc 54KB 49阅读

用户头像

is_751406

暂无简介

举报
commons-fileupload上传下载commons-fileupload上传下载 Struts2 commons-fileupload上传下载示例 Action代码: package com.yoyolg.action; ? import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java....
commons-fileupload上传下载
commons-fileupload上传下载 Struts2 commons-fileupload上传下载示例 Action代码: package com.yoyolg.action; ? import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; ? import org.apache.struts2.ServletActionContext; ? import com.opensymphony.xwork2.ActionSupport; ? /** ?* 文件上传下载示例Action ?* ?* @author 杨砚 ?*/ public class UpAndDownAction extends ActionSupport { ????/** ?????* 序列化编号 ?????*/ ????private static final long serialVersionUID = 1383989032015709062L; ? ????/** ?????* 存放上传文件的属性(上传页面中需在HTML的file标签中指定name属性为upload) ?????*/ ????File upload; ? ????/** ?????* 上传文件名(上传时无需在页面指定,由Struts2自动绑定) ?????*/ ????String uploadFileName; ? ????/** ?????* 随上传文件一起提交的单数据(该字段仅为演示在上传文件时提交的其他表单数据) ?????*/ ????String userName; ? ????/** ?????* 下载文件名 ?????*/ ????String downLoadfileName; ? ????/** ?????* 文件上传方法(Struts2 Action动态方法) ?????* ?????* @return String upLoadSuccess 上传成功后跳转到upLoad.jsp页面 ?????* @throws Exception ?????*/ ????public String upLoad() throws Exception { ????????// 打印用户名,演示随上传文件一起提交的表单数据 ????????System.out.println(this.userName); ????????if (this.upload != null) { ????????????// 文件存放路径为工程运行时根目录下的file文件夹 ????????????FileOutputStream fos = new FileOutputStream(ServletActionContext ????????????????????.getServletContext().getRealPath("/") ????????????????????+ "file\\" ????????????????????+ this.uploadFileName); ????????????FileInputStream fis = new FileInputStream(this.upload); ????????????// 以下语句通过输入流读取上传文件内容然后再通过输出流将内容输出到指定文件中 ????????????byte[] b = new byte[1024]; ????????????int len = 0; ????????????while ((len = fis.read(b)) > 0) { ????????????????fos.write(b, 0, len); ????????????} ????????} ????????return "upLoadSuccess"; ????} ? ????/** ?????* 文件下载Action方法 ?????* ?????* @return ?????* @throws Exception ?????*/ ????public String downLoad() throws Exception { ????????return "downLoadSuccess"; ????} ? ????/** ?????* Struts2自动调用的文件下载方法 ?????* ?????* @return ?????*/ ????public InputStream getDownloadFile() throws Exception { ????????// 将通过GET方式(超链接)提交的下载文件名解码(解决中文乱码) ????????// 页面上需要使用javaScript的encodeURI方法编码 ????????this.downLoadfileName = URLDecoder.decode(this.downLoadfileName, ????????????????"UTF-8"); ????????try { ????????????// 获取文件流,这里使用的是解码之后的文件名来获取, ????????????// 获取之后还需对downLoadfileName进行再次编码 ????????????FileInputStream fileInputStream = new FileInputStream( ????????????????????ServletActionContext.getServletContext().getRealPath("/") ????????????????????????????+ "file\\" + this.downLoadfileName); ????????????// 再次对文件名进行编码(否则下载文件名将出现乱码或无法下载) ????????????this.downLoadfileName = new String( ????????????????????this.downLoadfileName.getBytes(), "ISO-8859-1"); ????????????return fileInputStream; ????????} catch (UnsupportedEncodingException e) { ????????????e.printStackTrace(); ????????} catch (FileNotFoundException e) { ????????????e.printStackTrace(); ????????} ? ????????return null; ????} ? ????public File getUpload() { ????????return upload; ????} ? ????public void setUpload(File upload) { ????????this.upload = upload; ????} ? ????public String getUploadFileName() { ????????return uploadFileName; ????} ? ????public void setUploadFileName(String uploadFileName) { ????????this.uploadFileName = uploadFileName; ????} ? ????public String getUserName() { ????????return userName; ????} ? ????public void setUserName(String userName) { ????????this.userName = userName; ????} ? ????public String getDownLoadfileName() { ????????return downLoadfileName; ????} ? ????public void setDownLoadfileName(String downLoadfileName) { ????????this.downLoadfileName = downLoadfileName; ????} ? } 上传页面代码 <%@ page language="java" contentType="text/html; charset=UTF-8" ????pageEncoding="UTF-8"%> Insert title here ????下载页面 ????
注意事项:文件上传后要看上传效果,请查看运行时工程根目录下的file文件夹 ????如果要查看下载效果,请上传一个名为"测试文件.txt"的文件 ????
????????用户名
上传文件
????
下载页面代码 <%@ page language="java" contentType="text/html; charset=UTF-8" ????pageEncoding="UTF-8"%> Insert title here ????上传页面 ????
注意事项:本例中没有涉及数据库相关内容,下载前请先用上传页面上传一个名为 "测试文件.txt"的文件 ????
????下载测试文件 Struts2配置文件代码 ? ? ???? ???? ? ???? ???????? ????????????/upLoad.jsp ????????????/downLoad.jsp ???????????? ???????????????? ???????????????? ????????????????????attachment;filename="${downLoadfileName}" ???????????????? ???????????????? ????????????????downloadFile ???????????? ???????? ???? ? 本工程中涉及的jar包如下: commons-fileupload-1.2.1.jar、commons-io-1.4.jar、commons-logging-1.0.4.jar、freemarker-2.3.8.jar、ognl-2.6.11.jar、struts2-core-2.0.11.jar、xwork-2.0.4.jar 另外需要注意的是,struts2默认上传文件最大为2M,如果超出会报错,要修改最大上传大小,可以通过在struts.xml文件中添加以下语句实现: 设置后最大上传文件大小为100M。 使用common-fileupload组建实现文件上传下载功能, 封装了一个WebFileService的类 Java代码 收藏代码 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** *

Title: 处理文件上传下载的类

*

Description: * 通过设置long MAX_SIZE可以设置上传文件的大小限制 * 通过设置String[] allowedExt设置允许上传的文件类型 * 通过Map parameters获得表单域的信息 * 通过List fileInfoList获取上传的每个文件的详细信息 *

*

Copyright: Copyright (c) 2006, 2008 Royzhou Corporation.All rights reserved.

* @author royzhou * 2009-02-20 */ public class FileWebService { /** * 表单域的信息 */ private Map parameters = null; /** * 文件域的详细信息 */ private List fileInfoList = null; /** * 允许上传的文件大小 */ private long MAX_SIZE = 10*1024*1024; /** * 允许上传的文件类型 */ private String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "txt","doc", "docx", "mp3", "wma", "m4a" }; public FileWebService() { parameters = new HashMap(); fileInfoList = new ArrayList(); } /** * @param request * @param response * @param path 用户设置的保存路径 * 上传文件并获取表单域及文件域的详细信息 * @throws Exception */ public void upload(HttpServletRequest request, HttpServletResponse response, String path) throws Exception { /** * 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload */ DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(4096);// 设置上传文件时用于临时存放 文件的内存大小,这里是4K.多于的部分将临时存在硬盘 /** * 采用系统临时文件目录作为上传的临时目录 */ File tempfile = new File(System.getProperty("java.io.tmpdir")); diskFileItemFactory.setRepository(tempfile); /** * 用以上工厂实例化上传组件 * 设置最大上传尺寸 */ ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); fileUpload.setSizeMax(MAX_SIZE); /** * 调用FileUpload.settingHeaderEncoding(”UTF-8″),这项设置可以解决路径 或者文件名为乱码的问题。 * 设置输出字符集 */ fileUpload.setHeaderEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); /** * 从request得到 所有 上传域的列表 */ List fileList = null; try { fileList = fileUpload.parseRequest(request); } catch (FileUploadException e) { if (e instanceof SizeLimitExceededException) { /** * 文件大小超出限制 */ out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节

"); out.println("返回"); return; } e.printStackTrace(); } /** * 没有上传文件 */ if (fileList == null || fileList.size() == 0) { out.println("请选择上传文件

"); out.println("返回"); return; } /** * 得到所有上传的文件 * 对文件域操作 * 并保存每个文件的详细信息 */ Iterator fileItr = fileList.iterator(); Map fileInfo = null; while (fileItr.hasNext()) { FileItem fileItem = null; long size = 0; String userPath = null; String serverPath = null; String fileName = null; String fileExt = null; fileItem = (FileItem) fileItr.next(); /** * 忽略简单form字段而不是上传域的文件域(等) */ if (!fileItem.isFormField()) { /** * 得到文件的详细信息 * 客户端完整路径:userPath * 服务器端完整路径:serverPath * 大小:size * 文件名:fileName * 扩展名:fileExt * */ userPath = fileItem.getName(); size = fileItem.getSize(); if ("".equals(userPath) || size == 0) { out.println("请选择上传文件

"); out.println("返回 "); return; } fileName = userPath.substring(userPath.lastIndexOf("\\") + 1); fileExt = fileName.substring(fileName.lastIndexOf(".") + 1); /** * 文件类型是否合法 */ int allowFlag = 0; int allowedExtCount = allowedExt.length; for (; allowFlag < allowedExtCount; allowFlag++) { if (allowedExt[allowFlag].toLowerCase().equals(fileExt.toLowerCase())) break; } if (allowFlag == allowedExtCount) { out.println("请上传以下类型的文件

"); for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) out.println("*." + allowedExt[allowFlag].toLowerCase() + "   "); out .println("

返回"); return; } /** * 根据系统时间生成上传后保存的文件名 */ serverPath = path + System.currentTimeMillis() + "." + fileExt; try { /** * 保存文件 */ File diskPath = new File(path); if(!diskPath.exists()) { diskPath.mkdirs(); } File diskFile = new File(serverPath); if(!diskFile.exists()) { diskFile.createNewFile(); } fileItem.write(diskFile); out.println("文件上传成功. 已保存为: " + serverPath + "   文件大小: " + size + "字节

"); out.println("

"); out.println(" "); out.println(" "); out.println(" "); out.println("
"); } catch (Exception e) { e.printStackTrace(); } fileInfo = new HashMap(); fileInfo.put("size", String.valueOf(size)); fileInfo.put("userpath", userPath); fileInfo.put("name",fileName); fileInfo.put("ext", fileExt); fileInfo.put("serverpath", serverPath); fileInfoList.add(fileInfo); } else { String fieldName = fileItem.getFieldName(); /** * 在取字段值的时候,用FileItem.getString(”UTF-8″),这项设置可 以解决获取的表单字段为乱码的问题。 */ String value = fileItem.getString("UTF-8"); parameters.put(fieldName, value); } } } /** * 该方法支持支持国际化 * 但是文件名不能超过17个汉字 * 而且在IE6下存在bug */ public void downloadI18N(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html;charset=utf-8"); java.io.BufferedInputStream bis = null; java.io.BufferedOutputStream bos = null; String filePath = request.getParameter("filePath"); String fileName = request.getParameter("fileName"); System.out.println(fileName); try { long fileLength = new File(filePath).length(); fileName = URLEncoder.encode(fileName, "UTF-8"); response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + fileName); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(filePath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } /** * 支持中文,文件名长度无限制 * 不支持国际化 */ public void download(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("UTF-8"); java.io.BufferedInputStream bis = null; java.io.BufferedOutputStream bos = null; String filePath = request.getParameter("filePath"); String fileName = request.getParameter("fileName"); System.out.println(fileName); try { long fileLength = new File(filePath).length(); response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(filePath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } public List getFileInfoList() { return fileInfoList; } public void setFileInfoList(List fileInfoList) { this.fileInfoList = fileInfoList; } public Map getParameters() { return parameters; } public void setParameters(Map parameters) { this.parameters = parameters; } public String[] getAllowedExt() { return allowedExt; } public void setAllowedExt(String[] allowedExt) { this.allowedExt = allowedExt; } public long getMAX_SIZE() { return MAX_SIZE; } public void setMAX_SIZE(long max_size) { MAX_SIZE = max_size; } }
/
本文档为【commons-fileupload上传下载】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
热门搜索

历史搜索

    清空历史搜索