1. 程式人生 > 其它 >java web上傳下載檔案模組

java web上傳下載檔案模組

技術標籤:java基礎javaservletjavawebjsp

基於java web的檔案上傳下載工具

初步構想是實現從頁面選擇上傳路徑,若不選擇,則上傳到預設路徑,選擇上傳的檔案,點選上傳,上傳成功。

下載同理,若失敗,跳轉到提示失敗的頁面。

本專案解決了中文亂碼問題

完整專案連結:https://github.com/Hollake/summit_file

建議直接下載專案進行實操,注意需要自己更換預設路徑等,不更換必須填寫路徑

上傳介面示意圖

下載介面示意圖

檔案上傳程式碼

其思想為從頁面獲取表單資料,獲得檔案等相應資訊,進行讀取上傳。

package me.gacl.web.controller;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 UploadHandleServlet extends HttpServlet {
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳檔案的安全
                String defaultSavePath = "E:\\Java_code\\summit_file\\save";
                //訊息提示
                String message = "";
                String savePath = "";
            	String realSavePath = "";
                try{
                    //使用Apache檔案上傳元件處理檔案上傳步驟:
                    //1、建立一個DiskFileItemFactory工廠
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    //2、建立一個檔案上傳解析器
                    ServletFileUpload upload = new ServletFileUpload(factory);
                     //解決上傳檔名的中文亂碼
                    upload.setHeaderEncoding("UTF-8"); 
                    //3、判斷提交上來的資料是否是上傳表單的資料
                    if(!ServletFileUpload.isMultipartContent(request)){
                        //按照傳統方式獲取資料
                        return;
                    }
                    //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項
                    List<FileItem> list = upload.parseRequest(request);
                    for(FileItem item : list){
                        //如果fileitem中封裝的是普通輸入項的資料
                        if(item.isFormField()){
                            String  name = item.getFieldName();
                            //解決普通輸入項的資料的中文亂碼問題
                            savePath = item.getString("UTF-8");
                            realSavePath = makeSavePath(savePath,defaultSavePath);
                            File file = new File(realSavePath);
                            //判斷上傳檔案的儲存目錄是否存在
                            if (!file.exists() && !file.isDirectory()) {
                                System.out.println(defaultSavePath+"目錄不存在,需要建立");
                                //建立目錄
                                file.mkdir();
                            }
                            
                        }else{//如果fileitem中封裝的是上傳檔案
                            //得到上傳的檔名稱,
                            String filename = item.getName();
                            System.out.println(filename);
                            if(filename==null || filename.trim().equals("")){
                            	message= "檔案上傳失敗!";
                                request.setAttribute("message", message);
                	            request.getRequestDispatcher("/message.jsp").forward(request, response);
                            }
                            //注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,如:  c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt
                            //處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分
                            filename = filename.substring(filename.lastIndexOf("\\")+1);
                            //獲取item中的上傳檔案的輸入流
                            InputStream in = item.getInputStream();
                            //建立一個檔案輸出流
                            if(savePath == "" || savePath.isEmpty()) {
                        		realSavePath = defaultSavePath;
                        	}else {
                        		realSavePath = savePath;
                        	}
                            FileOutputStream out = new FileOutputStream(realSavePath + "\\" + filename);
                            //建立一個緩衝區
                            byte buffer[] = new byte[1024];
                            //判斷輸入流中的資料是否已經讀完的標識
                            int len = 0;
                            //迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料
                            while((len=in.read(buffer))>0){
                                //使用FileOutputStream輸出流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中
                                out.write(buffer, 0, len);
                            }
                            //關閉輸入流
                            in.close();
                            //關閉輸出流
                            out.close();
                            //刪除處理檔案上傳時生成的臨時檔案
                            item.delete();
                            message = "檔案上傳成功!";
                        }
                    }
                }catch (Exception e) {
                    message= "檔案上傳失敗!";
                    request.setAttribute("message", message);
    	            request.getRequestDispatcher("/message.jsp").forward(request, response);
                    e.printStackTrace();
                    
                }
                
                //獲取上傳檔案的目錄
	            String uploadFilePath = realSavePath;
	            //儲存要下載的檔名
	            Map<String,String> fileNameMap = new HashMap<String,String>();
	            //遞迴遍歷filepath目錄下的所有檔案和目錄,將檔案的檔名儲存到map集合中
	            ListFileServlet fileServlet = new ListFileServlet();
	            fileServlet.listfile(new File(uploadFilePath),fileNameMap);//File既可以代表一個檔案也可以代表一個目錄
	            //將Map集合傳送到listfile.jsp頁面進行顯示
	            request.setAttribute("fileNameMap", fileNameMap);
	            request.getRequestDispatcher("/listfile.jsp").forward(request, response);
    }
 
    private String makeSavePath(String savePath, String defaultSavePath) {
    	if(savePath == null || savePath.isEmpty()) {
    		return  defaultSavePath;
    	}else {
    		return  savePath;
    	}
	}
    
	public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        doGet(request, response);
    }
}

檔案下載處理程式碼

這裡只是對下載路徑是否為null等進行判斷,若為null則從預設路徑進行下載等,前臺展示功能必須呼叫ListFileServlet這個類來實現

package me.gacl.web.controller;
 
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.nio.*;

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 DownLoadHandleServlet extends HttpServlet {
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		    	//訊息提示
    			request.setCharacterEncoding("UTF-8");
		        String message = null;
		        String savePath = null;
            	String realSavePath = null;
                String defaultSavePath = "E:\\Java_code\\summit_file\\save\\";
                File defaultFile = new File(defaultSavePath);
                String downloadpath = request.getParameter("downloadpath");
                realSavePath = makeSavePath(downloadpath,defaultSavePath);
                File file = new File(realSavePath);
                //判斷上傳檔案的儲存目錄是否存在
                if (!file.exists() && !file.isDirectory()) {
                    message = "目錄或檔案不存在";
                    request.setAttribute("message", message);
    	            request.getRequestDispatcher("/message.jsp").forward(request, response);
                }

	            //儲存要下載的檔名
	            Map<String,String> fileNameMap = new HashMap<String,String>();
	            //遞迴遍歷filepath目錄下的所有檔案和目錄,將檔案的檔名儲存到map集合中
	            ListFileServlet fileServlet = new ListFileServlet();
	            fileServlet.listfile(new File(realSavePath),fileNameMap);//File既可以代表一個檔案也可以代表一個目錄
	            //將Map集合傳送到listfile.jsp頁面進行顯示
	            request.setAttribute("fileNameMap", fileNameMap);
	            request.getRequestDispatcher("/listfile.jsp").forward(request, response);
    }
 
    private String makeSavePath(String savePath, String defaultSavePath) {
    	if(savePath == null || savePath.isEmpty()) {
    		return  defaultSavePath;
    	}else {
    		return  savePath;
    	}
	}
    
	public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        doGet(request, response);
    }
}

下載頁面展示功能

package me.gacl.web.controller;
 
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 

public class ListFileServlet extends HttpServlet {
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //獲取上傳檔案的目錄
        String uploadFilePath = "E:\\Python_code";
        //儲存要下載的檔名
        Map<String,String> fileNameMap = new HashMap<String,String>();
        //遞迴遍歷filepath目錄下的所有檔案和目錄,將檔案的檔名儲存到map集合中
        listfile(new File(uploadFilePath),fileNameMap);//File既可以代表一個檔案也可以代表一個目錄
        //將Map集合傳送到listfile.jsp頁面進行顯示
        request.setAttribute("fileNameMap", fileNameMap);
        request.getRequestDispatcher("/listfile.jsp").forward(request, response);
    }
    
    /**
    * @Method: listfile
    * @Description: 遞迴遍歷指定目錄下的所有檔案
    * @Anthor:孤傲蒼狼
    * @param file 即代表一個檔案,也代表一個檔案目錄
    * @param map 儲存檔名的Map集合
    */ 
    public void listfile(File file,Map<String,String> map){
    	//map.put(file.getAbsolutePath(), file.getAbsolutePath());
        //如果file代表的不是一個檔案,而是一個目錄
        if(!file.isFile()){
            //列出該目錄下的所有檔案和目錄
            File files[] = file.listFiles();
            //遍歷files[]陣列
            for(File f : files){
                //遞迴
                listfile(f,map);
            }
        }else{
            /**
             * 處理檔名,上傳後的檔案是以uuid_檔名的形式去重新命名的,去除檔名的uuid_部分
                file.getName().indexOf("_")檢索字串中第一次出現"_"字元的位置,如果檔名類似於:9349249849-88343-8344_阿_凡_達.avi
                那麼file.getName().substring(file.getName().indexOf("_")+1)處理之後就可以得到阿_凡_達.avi部分
             */
            String realName = file.getName().substring(file.getName().indexOf("_")+1);
            //file.getName()得到的是檔案的原始名稱,這個名稱是唯一的,因此可以作為key,realName是處理過後的名稱,有可能會重複
            //map.put(file.getName(), realName);
            map.put(file.getAbsolutePath(), file.getAbsolutePath());
        }
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

下載功能

package me.gacl.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownLoadServlet extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //得到要下載的檔名
    	request.setCharacterEncoding("UTF-8");
        String fileName = request.getParameter("filename");
//        fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
        System.out.println("filename------"+fileName);
        String fileSaveRootPath = "E:\\Java_code";
        //得到要下載的檔案
        File file = new File(fileName);
        System.out.println("file------"+file);
        //如果檔案不存在
        if(!file.exists()){
            request.setAttribute("message", "您要下載的資源已被刪除!!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
        }
        
        //處理檔名
        String realname = fileName.substring(fileName.lastIndexOf("\\")+1);
        System.out.println("realname------"+realname);
        //設定響應頭,控制瀏覽器下載該檔案
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
        //讀取要下載的檔案,儲存到檔案輸入流
        FileInputStream in = new FileInputStream(fileName);
        //建立輸出流
        OutputStream out = response.getOutputStream();
        //建立緩衝區
        byte buffer[] = new byte[1024];
        int len = 0;
        //迴圈將輸入流中的內容讀取到緩衝區當中
        while((len=in.read(buffer))>0){
            //輸出緩衝區的內容到瀏覽器,實現檔案下載
            out.write(buffer, 0, len);
        }
        //關閉檔案輸入流
        in.close();
        //關閉輸出流
        out.close();
    }

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

jsp程式碼

這部分程式碼放置在github上了,連結如下:https://github.com/Hollake/summit_file

直接用eclipse開啟即可

參考:

https://blog.csdn.net/sxc1414749109/article/details/71430485