文件下载-springboot案例

一 下载本地文件

文件存放位置:

文件下载-springboot案例_第1张图片

 实现方法:

public static void downloadFile(HttpServletResponse response){
    String fileName = "测试文件.xls";
    String filePath = "/excel_file/test.xls";
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
    try {
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        boolean exists = classPathResource.exists();
        if(!exists){
            throw new RuntimeException("文件不存在:{}"+filePath);
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        os = response.getOutputStream();
        bis = new BufferedInputStream(classPathResource.getInputStream());
        int i = bis.read(buff);
        while (i != -1) {
            os.write(buff, 0, buff.length);
            os.flush();
            i = bis.read(buff);
        }
    } catch (FileNotFoundException e1) {
        e1.getMessage();
        throw new RuntimeException("系统找不到指定的文件,"+filePath);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bis != null) {
            try {
                bis.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二 下载网络文件(URL方式下载)

/**
	 * 文件下载
	 * @param id
	 * @return
	 */
	@RequestMapping(params = "download", method = RequestMethod.GET)
	public void download(@RequestBody JSONObject jsonObject,HttpServletRequest request,HttpServletResponse response) {
		logger.info("----------开始文件下载)接口信息接口-----------");
		try {
			String id = jsonObject.getString("id");
			Attach attach = attchService.findAttachById(id);
			URL url = new URL(attach.getUrl());  
	        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
	        conn.setConnectTimeout(3*1000); //设置超时间为3秒
	        //防止屏蔽程序抓取而返回403错误
	        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
	        response.setHeader("content-disposition", "attachment;filename="+ new String(attach.getPicName().getBytes(), "ISO-8859-1"));
	        //得到输入流
	        InputStream inputStream = conn.getInputStream();  
	        //获取自己数组
	        byte[] buffer = new byte[1024];  
	        int len = 0;  
	        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
	        while((len = inputStream.read(buffer)) != -1) {  
	            bos.write(buffer, 0, len);  
	        }  
	        byte[] getData = bos.toByteArray();  
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(getData);
	        if(inputStream!=null){
	            inputStream.close();
	        }
	        bos.close();  
	        outputStream.close();
		} catch (Exception e) {
			logger.error("下载失败:错误原因为:" + e);
		}
	}

三 下载多个文件,并压缩为zip文件

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gogbuy.web.util.ResultJson;
public class TestDemo {
	
	/**
	 * 1 下载导入模板
	 */
	@RequestMapping(params = "downLoadResFile")
	public ResultJson downLoadFile(HttpServletResponse response, HttpServletRequest request) {
		String dataDirectory = request.getServletContext().getRealPath("/");
		dataDirectory = dataDirectory + "upload/templateAndExample/";
		byte[] buffer = new byte[1024];
		FileInputStream fis =null;
		BufferedInputStream bis =null;
		try {
			response.setContentType("application/octet-stream");
			// type:  1 下载模板     2:下载示例  默认下载模板
			File file = new File(dataDirectory,"XXXX.zip");
			file = new File(dataDirectory,"XXXX.zip");
			response.addHeader("Content-Disposition","attachment;filename=" + new String("XXXXX.zip".getBytes(), "ISO-8859-1"));
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			OutputStream os = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				bis.close();
				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}

你可能感兴趣的:(java常见案例,大数据)