打流到前台。(下载文件)

来源:互联网 发布:遗传算法的基本思想 编辑:程序博客网 时间:2024/06/05 10:17

Java 部分

package com.gateguard.tp.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/work/test")
public class TestLoadController{
@RequestMapping(value="/download", produces = "application/json;charset=utf-8")
public  void downloadLocal(HttpServletResponse response,String filename,String filePath){
        // 下载本地文件
//        String fileName = "多条件查询文件.zip"; // 文件的默认保存名
  try {
       String fileName = new String(filename.getBytes("GBK"), "ISO-8859-1");
       // 读到流中
       InputStream inStream = new FileInputStream("E:/img14.png");// 文件的存放路径
       // 设置输出的格式
       response.reset();
       response.setContentType("bin");
       response.addHeader("Content-Disposition", "attachment; filename="+fileName);
       // 循环取出流中的数据
       byte[] b = new byte[100];
       int len;
       
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


前台下载部分

<a href="http://ip+项目名+/work/test/download.do?filename='img14.png'&filePath='E:/img14.png'">下载</a>

前台在线预览部分

<img src="http://ip+项目名+/work/test/download.do?filename='img14.png'&filePath='E:/img14.png'" style="width: 150px; height:100px;margin: 5px;">


原创粉丝点击