【Java】Java从网络读取图片并保存至本地

版权声明:【本文为博主原创文章或收集整理,未经博主允许不得转载】 https://blog.csdn.net/zsq520520/article/details/72466073

一、js代码:


代码如下:

/**
 * 点击下载当前图片
 * 
 */
 
function downloadThisImage(obj){
	var tid = $(obj).attr("file_tid");
	var fileSrc = $(obj).parent().prev().attr("src");
	window.location.href='../../file/toDownloadHmImage.do?tid='+tid+'&fileSrc='+fileSrc;
}

二、图片下载的公共方法

package com.zxct.edu.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletResponse;

public class ImagesUtil {
	public static void download2(HttpServletResponse response,String urlString, String filename) throws Exception {
		//new一个URL对象  
        URL url = new URL(urlString);  
        //打开链接  
        URLConnection conn = url.openConnection();  
         
        //超时响应时间为5秒  
        conn.setConnectTimeout(5 * 1000);  
        //通过输入流获取图片数据  
        InputStream inStream = conn.getInputStream();  
        //得到图片的二进制数据,以二进制封装得到数据,具有通用性  
        byte[] data = readInputStream(inStream);  
        //new一个文件对象用来保存图片,默认保存当前工程根目录  
        //File imageFile = new File(filename);  
        //创建输出流  
        OutputStream outStream = response.getOutputStream();
        //写入数据  
        outStream.write(data);  
        //关闭输出流  
        outStream.close();  
	}
	
	public static void download(HttpServletResponse response,String urlString, String filename) throws Exception {
	    // 构造URL
	    URL url = new URL(urlString);
	    // 打开连接
	    URLConnection con = url.openConnection();
	 
	    //超时响应时间为10秒  
        con.setConnectTimeout(10 * 1000);  
	    // 输入流
	    InputStream is = con.getInputStream();
	    // 1K的数据缓冲
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
	    // 输出的文件流
	    OutputStream os =response.getOutputStream();
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	    // 完毕,关闭所有链接
	    os.close();
	    is.close();
    }  
	
	public static byte[] readInputStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        //创建一个Buffer字符串  
        byte[] buffer = new byte[1024];  
        //每次读取的字符串长度,如果为-1,代表全部读取完毕  
        int len = 0;  
        //使用一个输入流从buffer里把数据读取出来  
        while( (len=inStream.read(buffer)) != -1 ){  
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度  
            outStream.write(buffer, 0, len);  
        }  
        //关闭输入流  
        inStream.close();  
        //把outStream里的数据写入内存  
        return outStream.toByteArray();  
    }
}
注:download和download2方法均能实现下载。

三、Controller接口方法:

/**
	 * 下载图片文件
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @author zhangsq
	 */
	@RequestMapping("/toDownloadHmImage.do")
	public void toDownloadHmImage(HttpServletRequest request, HttpServletResponse response,
			ModelMap model,String fileSrc,String tid) throws ServletException, IOException {
		String filePath = fileSrc.substring(0,fileSrc.indexOf("?"));
		String realname = filePath.substring(filePath.lastIndexOf("/")+1);
		// 设置响应头,控制浏览器下载该文件
		response.reset();
		response.setStatus(HttpServletResponse.SC_OK); 
		response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
		try {
			ImagesUtil.download(response,filePath, realname);
		} catch (Exception e) {
			e.printStackTrace();
			ServletOutputStream sos = null;
			try {
				response.setContentType("text/html;charset=utf-8");
				sos = response.getOutputStream();
				sos.write("<script>alert('下载失败,请与管理员联系~~');</script>".getBytes());
				sos.flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}finally{
				if(null != sos){
					try {
						sos.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		} 
        
	}


猜你喜欢

转载自blog.csdn.net/zsq520520/article/details/72466073
今日推荐