1. 程式人生 > 實用技巧 >java檔案下載

java檔案下載

package com.tt.rhms.sys.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @Author xl
* 檔案下載
*/
@RestController
public class DownloadFile {
@GetMapping("lz/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
Date date = new Date();
String time = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
String fileName = "";//下載後的檔名
String sourceFilePath = "D:\\download\\0.txt";//下載資源路徑
String sourceFilePath1 = "D:\\download\\1.jfif";//下載資源路徑
String sourceFilePath2 = "D:\\download\\2.jpg";//下載資源路徑
String sourceFilePath3 = "D:\\download\\3.doc";//下載資源路徑
String sourceFilePath4 = "D:\\download\\4.mp3";//下載資源路徑
String suffix = sourceFilePath4.substring(sourceFilePath4.lastIndexOf("."));
fileName = time + suffix;
//配置檔案下載
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
byte[] buff = new byte[1024];
//建立緩衝輸入流
BufferedInputStream bis = null;
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
//資源路徑
bis = new BufferedInputStream(new FileInputStream(new File(sourceFilePath4)));
int read = bis.read(buff);
while (read != -1) {
outputStream.write(buff, 0, buff.length);
//outputStream.flush(); //報錯:org.eclipse.jetty.io.eofexception,控制檯報錯,但功能正常使用
read = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
return "下載失敗";
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "下載成功";
}
}