All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.luues.util.down.DownUtil Maven / Gradle / Ivy

There is a newer version: 1.3.0.5.RELEASE
Show newest version
package com.luues.util.down;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownUtil {

    public static void downFile(HttpServletResponse response, String path, String name) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = name;
            // 取得文件的后缀名。
            // 以流的形式下载文件。
            //InputStream fis = new BufferedInputStream(new FileInputStream(path));
            InputStream fis = new FileInputStream(path);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "iso-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 返回图片直接显示
     * @param
     * 		path(n) 图片网络路径
     */
    public static void writePictures(HttpServletResponse response, String path) {
        URL url = null;
        InputStream is = null;
        try {
            // 构建图片的url地址
            url = new URL(path);
            // 开启连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置超时的时间,5000毫秒即5秒
            conn.setConnectTimeout(50000);
            // 设置获取图片的方式为GET
            conn.setRequestMethod("GET");
            // 响应码为200,则访问成功
            if (conn.getResponseCode() == 200) {
                // 获取连接的输入流,这个输入流就是图片的输入流
                is = conn.getInputStream();
                ImageIO.write(ImageIO.read(is), "JPEG", response.getOutputStream());
            }
        } catch (Exception e) {
            // 告诉handler,图片已经下载失败
            e.printStackTrace();
        } finally {
            // 在最后,将各种流关闭
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy