点击查看文件上传
ssm框架从页面下载文件
@Controller
@RequestMapping("/atta")
public class AttachmentController {
@Autowired
private AttachmentService attach;
//文件下载
@RequestMapping(value = "/down/{id}")
//从页面文件下载返回值必须为 ResponseEntity<byte[]>
public ResponseEntity<byte[]> getDownload(@PathVariable("id") Integer id, HttpSession request){
//获取要下载的东西的路径
ServletContext servletContext = request.getServletContext();
String realPath = servletContext.getRealPath("/upload");
System.out.println(realPath);
File file=new File(realPath);
//根据id从数据库查到该数据,该数据中有下载文件的名字
Attachment look = attach.getLookAttachment(id);
//查看realPath 的路径下的所有文件,封装到File数组中
File[] files = file.listFiles();
//存放文件路径
String readPath="";
//存放文件名称
String fileName="";
//循环所有文件
for (int i = 0; i < files.length; i++) {
//当该文件的名字和我们从数据库中查到的名字相同时
if (files[i].getName().equals(look.getPath())){
//吧文件名称存入fileName
fileName+=files[i].getName();
//吧文件路径存放到readPath
readPath+=servletContext.getRealPath("/upload/"+files[i].getName());
}
}
try {
System.out.println(readPath);
//吧文件读入到内存中
FileInputStream input=new FileInputStream(new File(readPath));
//放到字节数组中 这里用input.available() 直接序列话到数组中
byte[] body=new byte[input.available()];
//读进来
input.read(body);
//设置状态
HttpStatus statusCode=HttpStatus.OK;
//创建ResponseEntity<byte[]> 所需的参数
MultiValueMap<String, String> heard=new HttpHeaders();
//设置fileName 的格式编码
fileName=new String(fileName.getBytes("gbk"),"iso8859-1");
//设置响应头Content-Disposition的信息
heard.add("Content-Disposition","attachment;filename="+fileName);
//吧参数放入 ResponseEntity<byte[]> 用于文件下载的对象中
ResponseEntity<byte[]> result=new ResponseEntity<byte[]>( body, heard ,statusCode);
//返回
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
谢谢观看