ssm框架从页面下载文件

点击查看文件上传
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;
    }

谢谢观看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值