码迷,mamicode.com
首页 > Web开发 > 详细

Servlet方式实现文件的上传和下载

时间:2015-02-09 15:26:45      阅读:523      评论:0      收藏:0      [点我收藏+]

标签:

文件的上传和下载需要两个jar包  commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar

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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Servlet_FileUpLoad</title>
</head>
<body>
	<form action="fileUp.action" enctype="multipart/form-data" method="post">
		<input type="file" name="file">
		<input type="submit" value="上传">
	</form>
        <form action="fileLoad.action">
		<input type="submit" value="下载">
	</form>
</body>
</html>

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

	<!-- 上传文件 -->
	<servlet>
		<servlet-name>fileUp</servlet-name>
		<servlet-class>com.eyang.servlet.FileUpServlet</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>fileUp</servlet-name>
		<url-pattern>/fileUp.action</url-pattern>
	</servlet-mapping>
	
	<!-- 下载文件 -->
	<servlet>
		<servlet-name>fileLoad</servlet-name>
		<servlet-class>com.eyang.servlet.FileLoadServlet</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>fileLoad</servlet-name>
		<url-pattern>/fileLoad.action</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

上传Servlet

package com.eyang.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUpServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8"); // 设置编码

		// 获得磁盘文件条目工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 获取文件需要上传到的路径
		String path = request.getSession().getServletContext().getRealPath("/upload");

		// 若upload目录不存在、则会创建该目录、
		File tmpFile = new File(path);
		if(!tmpFile.exists()) {
			tmpFile.mkdir();
		}
		
		// 输出文件上传后的路径
		System.out.println("path = " + path);
		// 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
		// 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
		/**
		 * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem
		 * 格式的 然后再将其真正写到 对应目录的硬盘上
		 */
		factory.setRepository(new File(path));
		// 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
		factory.setSizeThreshold(1024 * 1024);

		// 高水平的API文件上传处理
		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			// 可以上传多个文件
			List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

			for (FileItem item : list) {
				// 获取表单的属性名字
				String name = item.getFieldName();

				// 如果获取的 表单信息是普通的 文本 信息
				if (item.isFormField()) {
					// 获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
					String value = item.getString();

					request.setAttribute(name, value);
				}
				// 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
				else {
					/**
					 * 以下三步,主要获取 上传文件的名字
					 */
					// 获取路径名
					String value = item.getName();
					// 索引到最后一个反斜杠
					int start = value.lastIndexOf("\\");
					// 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
					String filename = value.substring(start + 1);

					//request.setAttribute(name, filename);

					// 真正写到磁盘上
					// 它抛出的异常 用exception 捕捉

					// item.write( new File(path,filename) );//第三方提供的

					// 手动写的
					OutputStream out = new FileOutputStream(new File(path, filename));

					InputStream in = item.getInputStream();

					int length = 0;
					byte[] buf = new byte[1024];

					System.out.println("获取上传文件的总共的容量:" + item.getSize());

					// in.read(buf) 每次读到的数据存放在 buf 数组中
					while ((length = in.read(buf)) != -1) {
						// 在 buf 数组中 取出数据 写到 (输出流)磁盘上
						out.write(buf, 0, length);

					}

					in.close();
					out.close();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

文件下载Servlet

package com.eyang.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileLoadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String rootPath = request.getSession().getServletContext().getRealPath("/upload");
		File file = new File(rootPath + "/qianyesong.jpg");
		
		if(file.exists()) {
			String filename = URLEncoder.encode(file.getName(), "UTF-8");
            response.reset();
            response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            int fileLength = (int) file.length();
            response.setContentLength(fileLength);
            
            /*如果文件长度大于0*/
            if (fileLength != 0) {
                /*创建输入流*/
                InputStream inStream = new FileInputStream(file);
                byte[] buf = new byte[4096];
                /*创建输出流*/
                ServletOutputStream servletOS = response.getOutputStream();
                int readLength;
                while (((readLength = inStream.read(buf)) != -1)) {
                    servletOS.write(buf, 0, readLength);
                }
                inStream.close();
                servletOS.flush();
                servletOS.close();
            }
            
		} else {
			System.out.println("文件不存在");
		}
	}
}

  

Servlet方式实现文件的上传和下载

标签:

原文地址:http://www.cnblogs.com/keryang/p/4281541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!