根据图片地址下载图片到本地服务器 将本地服务器图片输出到浏览器下载

一:

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"));

}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值