**文件的上传和下载**

文件上传

  •   1、前台页面
      	表单实现文件上传
      	1、表单的提交类型为method="POST"
      	2、表单类型设置为enctype="multipart/form-data"
      	3、表单元素设置name属性值
    
  •   2、后台代码
      	首先需要导入第三方 jar 包,http://commons.apache.org/
      	下 载commons-io 和 commons-fileupload 两个 jar 的资源。解压并导入到项目中。
      	commons-fileupload.jar 是文件上传的核心包
      	commons-io.jar 是 filefupload 的依赖包,同时又是一个工具包。
      		实现步骤:
      		DiskFileItemFactory – 设置磁盘空间,保存临时文件。只是一个工具类
      		ServletFileUpload – 文件上传的核心类,此类接收 request,并解析
      		ServletFileUpload.parseRequest(request); – List 解析 request
      		1、 创建一个 DiskFileItemFactory 工厂类,并制定临时文件和大小
      		2、 创建 ServletFileUpload 核心类,接收临时文件,做请求的转换
      		3、 通过 ServletFileUpload 类转换原始请求,得到 FileItem 集合
      		4、 遍历集合中的各个元素并处理
      		5、 判断每个元素是否是普通表单项,如果是则按照普通表单项处理
      		6、 如果不是普通表单项,则是文件,通过处理的方式进行处理(上传)
    

    代码示例:

    public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	System.out.println("文件上传...");
    	
    	// 设定编码,可以获取中文文件名
    	request.setCharacterEncoding("UTF-8");
    	
    	// 获取tomcat下的upload目录的路径
    	String path = getServletContext().getRealPath("/upload");
    	// 临时文件目录
    	String tempPath = getServletContext().getRealPath("/temp");
    	
    	// 检查我们是否有文件上传请求
    	// boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    	
    	// 1、声明DiskFileItemFactory工厂类,用于在指定磁盘上设置一个临时目录
    	DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, new File(tempPath));
    	
    	// 2、声明ServletFileUpload,接收上面的临时文件。也可以默认值
    	ServletFileUpload uplaod = new ServletFileUpload(disk);
    	
    	
    	
    	try {
    		// 3、解析request,返回FileItem的集合
    		List<FileItem> list = uplaod.parseRequest(request);
    		// 判断集合是否为空
    		if (list.size() > 0) {
    			// 遍历FileItem的集合,判断是普通表单项还是文件上传
    			for (FileItem file : list)
    				// 判断是否是普通的表单项
    				if (file.isFormField()) {
    					
    					String fieldName = file.getFieldName();
    					// 中文乱码,此时还需要指定获取数据的编码方式
    					// String value = file.getString();
    					String value = file.getString("UTF-8");
    					System.out.println(fieldName + "=" + value);
    					
    				} else { // 说明是一个文件
    					// 获取文件本身的名称
    					String fileName = file.getName();
    					System.out.println(file.getFieldName());
    					// 处理文件名称
    					fileName =  fileName.substring(fileName.lastIndexOf("\\") + 1);
    					System.out.println("old Name : " + fileName);
    					// 修改名称 (得到文件的后缀名)
    					String extName =  fileName.substring(fileName.lastIndexOf("."));
    					// 生成随机的文件名 + 文件后缀
    					String newName =  UUID.randomUUID().toString().replace("-", "") + extName;
    					// 保存新的名称,并写出到新文件中
    					file.write(new File(path + "/" + newName));
    					System.out.println("文件名是:" + fileName);
    					System.out.println("文件大小是:" + file.getSize());
    					// 删除临时文件
    					file.delete();
    				}
    		}
    	} catch (FileUploadException e) {
    		e.printStackTrace();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    

文件下载

  •   步骤:
      Step1:需要通过 HttpServletResponse.setContentType 方法设置 Content-type 头字段的值,为浏览器无法使用某种方式或激活某个程序来处理的 MIME 类型,
      	例 如 ”application/octet-stream” 或 ”application/x-msdownload” 等
      Step2:需要通过 HttpServletResponse.setHeader 方法设置Content-Disposition 头的值 为”attachment;filename=文件名”
      Step3: 读取下载文件,调用 HttpServletResponse.getOutputStream 方法返回的 OutputStream 对象来向客户端写入附件内容。
    
  •   代码示例
      public class DownloadServlet extends HttpServlet {
      	private static final long serialVersionUID = 1L;
    
      	protected void service(HttpServletRequest request, HttpServletResponse response) throws 	ServletException, IOException {
      
      	// 设置请求的编码
      	request.setCharacterEncoding("UTF-8");
      	// 得到要下载的文件名
      	String fileName = request.getParameter("fileName");
      	// 得到文件存放咋服务器中的真实路径
      	String filePath = request.getServletContext().getRealPath("/upload/" + fileName);
      	// 通过路径得到file对象
      	File file = new File(filePath);
      	// 判断文件是否存在,并且是一个标准文件
      	if (file.exists() && file.isFile()) {
      	
      		// 设置相应类型 application/octet-stream
      		response.setContentType("application/x-msdownload");
      		// 设置头信息
      		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
      		// 得到文件的输入流
      		InputStream in = new FileInputStream(file);
      		// 得到字节输出流
      		ServletOutputStream out = response.getOutputStream();
      		// 定义字节数组 和 长度
      		byte[] bytes = new byte[1024];
      		int len = 0;
      		// 遍历
      		while((len = in.read(bytes)) != -1) {
      			out.write(bytes, 0, len);
      		}
      		// 关闭资源
      		out.close();
      		in.close();
      	
      	} else {
      		System.out.println("文件不存在!");
      }
      
      }
    
      }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值