1. 程式人生 > >- springmvc實現檔案下載

- springmvc實現檔案下載

前言:

        實現檔案下載的功能網上有很多案例。在這小編隨筆寫一篇關於springmvc實現檔案下載的隨筆!如果有興趣的同學可以看一下,沒有太多的技術要點。

實現步驟:        

        先說說開發的思路,有思路了開發也就簡單了。沒思路開發就很難了!

        一:我們說是下載檔案吧,直接一個給前臺一個url不就好了!這種方法確實可以,但是如果瀏覽器能解析的檔案的話就會直接在瀏覽器打開了。比如:你想下載一個txt的文字,可是瀏覽器可以解析就給你直接打開了。這不符合吧!所以第一步我們要先確定檔案是否是都下載,還是允許瀏覽器解析。

        二:確定了之後,我們在前臺放一個連結!後臺用流的方式回寫回去。(注意:儘量用快取流來實現,這樣高效一些,如果位元組流且設定的讀取不大,下載大檔案時,呵呵!)

程式碼:

        這裡是filUtils類,主要放關於檔案的東西。

package com.wen.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class FileUtil {
	
	/**
	 * 讀取到位元組陣列2
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray2(String filePath) throws IOException {

		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}

		FileChannel channel = null;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			channel = fs.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
			while ((channel.read(byteBuffer)) > 0) {
				// do nothing
				// System.out.println("reading");
			}
			return byteBuffer.array();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
         這個是檔案下載類(設定下載的方式等):
package com.wen.util;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;


/**
 * 下載檔案
 * @version
 */
public class FileDownload {

	/**
	 * @param response 
	 * @param filePath		//檔案完整路徑(包括檔名和副檔名)
	 * @param fileName		//下載後看到的檔名
	 * @return  檔名
	 */
	public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{  
		     
		    byte[] data = FileUtil.toByteArray2(filePath);  
		    fileName = URLEncoder.encode(fileName, "UTF-8");  
		    response.reset();  
		    //保證檔案都是下載的,不是解析
		    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
		    response.addHeader("Content-Length", "" + data.length);  
		    response.setContentType("application/octet-stream;charset=UTF-8");
		    //緩衝流
		    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
		    outputStream.write(data);  
		    //重新整理快取,不懂就理解為2胖子一起出門給堵住了,你一腳踹過去讓他們出去
		    outputStream.flush();  
		    //保持好習慣,用完就關掉
		    outputStream.close();
		    response.flushBuffer();
		    
		} 

}
            接下來就是我們springmvc的檔案下載類了!
package com.wen.controller.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.wen.bean.ExtendFreaction;
import com.wen.bean.FileInformation;
import com.wen.bean.Freaction;
import com.wen.service.user.AdminServices;
import com.wen.service.user.UserServices;
import com.wen.shiro.manager.ShiroManager;
import com.wen.util.Constant;
import com.wen.util.FileDownload;
import com.wen.util.ObjectExcelView;

@Controller
public class AdminController {
	@Resource
	AdminServices adminService;
	@Resource
	UserServices userServices;



	/**
	 * 使用者下載檔案
	 * @return
	 */
	@RequestMapping(value = "downLoadFile")
	public void downLoadFile(HttpServletResponse response, Integer  id) {	
		//從資料庫查檔案的資訊
		FileInformation fileInformation=adminService.getFileInformation(id);
		
		try {//開始下載了唄
			FileDownload.fileDownload(response, fileInformation.getPath(), fileInformation.getFilename());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
}
        附:FileInformation類
package com.wen.bean;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;



public class FileInformation {
	private int id;
	private String filename;
	private String path;
	private String filetype;
	
	private Date time;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getFiletype() {
		return filetype;
	}

	public void setFiletype(String filetype) {
		this.filetype = filetype;
	}
	
	public Date getTime() {
		return time;
	}

	public void setTime(Date time) {
		this.time = time;
	}

	@Override
	public String toString() {
		return "FileInformation [id=" + id + ", filename=" + filename + ", path=" + path + ", filetype=" + filetype
				+ ", time=" + time + "]";
	}

}

        後臺程式碼就這麼簡單,接下來看看前臺的程式碼:

            對應檔案資訊加一個這個。就可以實現了!

    <a href="javascript:void;"  title="下載" onclick="downLoad('${fileInfo.id}');">下載</a>
		//下載檔案
		function downLoad(file_id) {
			
			window.location.href = 'downLoadFile.action?id='+file_id;
		}

        測試:


        檔案:

    

        這樣就實現檔案下載的功能了!

總結:

        springmvc做檔案下載很簡單。其實,用普通的jsp+servlet也是可以用這個方法來這樣做,只是我寫的demo裡用了springmvc,所以就叫springmvc咯!下一次,小編會寫ecxel的操作,並共享一些util工具類,方便大家編寫程式碼,不需要重複造輪子!

        程式人生,與君共勉