根據圖片地址下載圖片到本地服務器 將本地服務器圖片輸出到瀏覽器下載

一:

1.根據圖片地址下載圖片到本地服務器

2.刪除本地服務器上的圖片

       

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DownLoadFileUtil {

    /**
     * 根據文件url地址下載文件
     */
    private static final Logger LOG = Logger.getLogger(DownLoadFileUtil.class);
    public static JSONObject downLoadFile(String urlPath,String downloadDir)
    {
        JSONObject jsonObject = new JSONObject();
        File file = null;
        try {
            // 統一資源
            URL url = new URL(urlPath);
            // 連接類的父類,抽象類
            URLConnection urlConnection = url.openConnection();
            // http的連接類
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            // 設定請求的方法,默認是GET
            httpURLConnection.setRequestMethod("POST");
            // 設置字符編碼
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打開到此 URL 引用的資源的通信鏈接(如果尚未建立這樣的連接)。
            httpURLConnection.connect();
            // 文件大小
            //int fileLength = httpURLConnection.getContentLength();
            // 文件名
            String filePathUrl = httpURLConnection.getURL().getFile();
            String[] names = filePathUrl.split("\\.");
            String tempNum = (int) (Math.random() * 100000) + "";
            String uploadFileName = tempNum + System.currentTimeMillis() + "." + names[names.length - 1];

            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            String path = downloadDir  + fileDate()+ uploadFileName;
            file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(file);
            int size = 0;
            byte[] buf = new byte[1024];
            while ((size = bin.read(buf)) != -1) {
                out.write(buf, 0, size);
            }
            bin.close();
            out.close();
            jsonObject.put("errcode",0);
            jsonObject.put("file",path);
        } catch (Exception e) {
            jsonObject.put("errcode",-1);
            LOG.info(e.getMessage());
        }
        return  jsonObject;
    }

    /**
     * 根據文件在本服務器絕對路徑刪除服務器文件
     * */
    public static boolean deleteFile(String fileAddress)
    {
        boolean isTrue=false;
        File file = new File(fileAddress);
        if (file.exists() && file.isFile()) {
            isTrue = file.delete();
        }
        return isTrue;
    }

    private static String fileDate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(new Date()) + "/";
    }
}

二:將本地服務器圖片輸出到瀏覽器下載

 @ResponseBody
    @RequestMapping(method = RequestMethod.GET, params = "action=downFile")
    public void downFile( @RequestParam("fileUrl在本地服務器絕對地址") String fileUrl, HttpServletResponse response) {
String agent = request.getHeader("User-Agent");
                if (agent.contains("MSIE")) {
                    // IE瀏覽器
                    fileName = URLEncoder.encode(fileName, "utf-8");
                    fileName = fileName.replace("+", " ");
                } else if (agent.contains("Firefox")) {
                    // 火狐瀏覽器
                    BASE64Encoder base64Encoder = new BASE64Encoder();
                    fileName = "=?utf-8?B?"
                            + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";
                } else {
                    // 其它瀏覽器
                    fileName = URLEncoder.encode(fileName, "utf-8");
                }
                response.setContentType("application/x-download");//告知瀏覽器下載文件,而不是直接打開,瀏覽器默認爲打開
                response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");//下載文件的名稱

String path = fileUrl;
                InputStream in = new FileInputStream(path);
                OutputStream out = response.getOutputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                in.close();
                DownLoadFileUtil.deleteFile(jsonObject.getString("file"));

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章