java 獲取resource下的靜態資源文件

1、後臺下載文件比較簡單的邏輯步驟

(1)、準備靜態模板文件:把靜態資源文件放到src/main/resource路徑下,如:excelTmp/studentDemo.xlsx

(2)、實現邏輯:先獲取靜態資源的url路徑,方法兩種,但各有些小問題

  第一種:

import java.net.URL; import org.springframework.core.io.ClassPathResource;
URL url = new ClassPathResource("excelTmp/studentDemo.xlsx").getURL();

這種方法在參數的路徑上,不能包含中文(實現功能可以,推薦使用)

第二種:

URL url = getClass().getClassLoader().getResource("excelTmp/學生模板.xlsx");

這種方法在本地tomcat運行可以準確的獲取靜態資源文件,但親測在linux服務器上獲取的url爲null(本人的測試的項目,調用處被打包在lib下的jar包中,對於存在一些特殊情況下會出問題,因此,不推薦使用)

(3)、獲取資源後見的url後,獲取文件,轉文件的字節數組,通過respone的輸出流,將文件字節數組輸出

(4)、前端通過a標籤,將href指定爲接口地址,即可實現下載文件的效果(所以要求可以get請求)

(5)、調用實現詳細代碼如下

import com.hx.platform.annotation.BusiAnnotation;
import com.hx.platform.education168.ptgl.common.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;


@RestController
@RequestMapping("/eduStudent")
@BusiAnnotation(busiModule = "學生管理")
public class StudentController {

	// 日誌
	private static Logger logger = LoggerFactory.getLogger(StudentController.class);

	@RequestMapping("/downloadExcel11")
	public void testStream11(String excelType, HttpServletRequest req, HttpServletResponse resp) {
		try {
			URL url = null;
			if("1".equals(excelType)){
				url = getClass().getClassLoader().getResource("excelTmp/學生模板.xlsx");
			} else if("2".equals(excelType)) {
				url = getClass().getClassLoader().getResource("excelTmp/家長模板.xlsx");
			} else if("3".equals(excelType)) {
				url = getClass().getClassLoader().getResource("excelTmp/教師模板.xlsx");
			}
			logger.info("url:" + url);
			// 通過url獲取File的絕對路徑
			File f = new File(url.getFile());
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/x-download;charset=utf-8");
			resp.setHeader("Content-disposition",  URLEncoder.encode(f.getName(), "UTF-8"));
			//mime類型
			resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			resp.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(f.getName(), "UTF-8"));
			resp.setHeader("Pragma", "No-cache");
			//從內存中寫出來
			OutputStream outputStream = resp.getOutputStream();
			outputStream.write(FileUtil.file2byte(f));
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping("/downloadExcel")
	public void testStream(String excelType, HttpServletRequest req, HttpServletResponse resp) {
		try {
			URL url = null;
			if("1".equals(excelType)){
				url = new ClassPathResource("excelTmp/studentDemo.xlsx").getURL();
			} else if("2".equals(excelType)) {
				url = new ClassPathResource("excelTmp/parentDemo.xlsx").getURL();
			} else if("3".equals(excelType)) {
				url = new ClassPathResource("excelTmp/teacherDemo.xlsx").getURL();
			}
			logger.info("url:" + url);
			// 通過url獲取File的絕對路徑
			File f = new File(url.getFile());
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/x-download;charset=utf-8");
			resp.setHeader("Content-disposition",  URLEncoder.encode(f.getName(), "UTF-8"));
			//mime類型
			resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			resp.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(f.getName(), "UTF-8"));
			resp.setHeader("Pragma", "No-cache");
			//從內存中寫出來
			OutputStream outputStream = resp.getOutputStream();
			outputStream.write(FileUtil.file2byte(f));
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

附:文件轉字節數組代碼

import java.io.*;

/**
 * 用於文件和流轉換需要
 */
public class FileUtil {

	/**
	 * 將文件轉換成byte數組
	 * @param
	 * @return
	 */
	public static byte[] file2byte(File tradeFile){
		byte[] buffer = null;
		try
		{
			FileInputStream fis = new FileInputStream(tradeFile);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1)
			{
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		}catch (FileNotFoundException e){
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}
		return buffer;
	}
}

(6)、測試效果:

(7)、以上下載模板文件成功,總結就是後端獲取靜態文件,轉文件流通過瀏覽器響應參數response來輸出文件流,前端通過a標籤來觸發即可。學海無涯苦作舟!

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章