Servlet方式實現檔案的上傳和下載

來源:互聯網
上載者:User

標籤:

檔案的上傳和下載需要兩個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方式實現檔案的上傳和下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.