Servlet方式實現文件的上傳和下載

文件的上傳和下載須要兩個jar包  commons-fileupload-1.2.2.jar和commons-io-2.0.1.jarhtml

JSP頁面java

<%@ 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配置web

<?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>

上傳Servletexpress

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();
		}
	}
}

文件下載Servletapache

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("文件不存在");
		}
	}
}
相關文章
相關標籤/搜索