文件下载:
由于业务需要,今天写了个文件下载,其实还挺容易的,就是简单的io操作,下面有个简单小测试,有需要的可以瞄一瞄
实例:
package com.hy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@Controller
public class FileDownload{
/***
* @title 下载文件
* @author sjt
* @param response
*/
@RequestMapping("/download")
public void download(HttpServletResponse response){
//文件真实路径
String path = "";
//设置文件相应类型
response.setContentType("multipart/form-data");
//设置文件头、要保存的文件名称
response.setHeader("Content-Disposition","attachment;fileName="+"模板.jpg");
OutputStream outputStream = null;
FileInputStream inputStream = null;
//把文件路径转换为文件对象
File file = new File(path);
try {
//将文件转换为流
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
int b = -1;
//设置文件流缓冲区
byte[] bytes = new byte[1024];
while ((b=inputStream.read(bytes)) != -1){
//将文件写入输出流
outputStream.write(bytes,0,b);
}
//强制将文件流刷出缓冲区
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
//关闭流
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}