Java springboot 控制类
@RequestMapping(value = "downloadFile", method = RequestMethod.GET)
@ResponseBody
public void downloadFile( HttpServletResponse resp, String filename){
String downloadName = filename + ".apk";
downloadFileTool.download(resp, filename, downloadName);
}
Java 新建 downloadFileTool
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
public class downloadFileTool {
/**
* @param resp
* @param name 文件真实名字
* @param downloadName 文件下载时名字
*/
public static void download(HttpServletResponse resp, String name, String downloadName) {
String fileName = null;
try {
fileName = new String(downloadName.getBytes("GBK"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String path ="D:\\mtapp\\"+name+".apk";
File file = new File(path);
resp.reset();
resp.setContentType("application/octet-stream");
resp.setCharacterEncoding("utf-8");
resp.setContentLength((int) file.length());
resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = resp.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}