java 从url中读取文件 并写入文件 实现图片文件读取跨域



import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;



/**
 * 	文件处理工具类
 * @author lhz
 * 2020-8-28 10:14:18
 *
 */
public class FileUtils  {
	
	/**
	 *  将 文件从网络环境中读取
	 * @param fileUrl
	 * @return
	 * @throws IOException
	 */
	public static BufferedInputStream readFileFromNet(String fileUrl) throws IOException {
		if(StringUtils.isBlank(fileUrl)) {
			return null;
		}
		URL url;
		url = new URL(fileUrl);
		return  new BufferedInputStream(url.openStream());
	}
	
	/**
	 * 将文件写入 response
	 * 没有关闭流
	 * @param bis
	 * @param response
	 * @throws IOException 
	 */
	public static void writeFile(BufferedInputStream bis,boolean bis_closeFlag,String fileName,HttpServletResponse response) throws IOException {
		if(bis==null) {
			return ;
		}
		int len=0;
		byte[ ] bs=new byte[2048];
		if(StringUtils.isNotBlank(fileName)) {
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
		}
		
		while((len=bis.read(bs))!=-1) {
			response.getOutputStream().write(bs,0,len);
		}
		if(bis_closeFlag) {
			bis.close();
		}
		response.getOutputStream().flush();
	}
	
	/**
	 * 写入文件
	 * @param bis
	 * @param os
	 * @param bis_closeFlag
	 * @throws IOException
	 */
	public static void writeFile(BufferedInputStream bis,OutputStream os,boolean bis_closeFlag) throws IOException {
		if(bis==null) {
			return ;
		}
		int len=0;
		byte[ ] bs=new byte[2048];
		while((len=bis.read(bs))!=-1) {
			os.write(bs,0,len);
		}
		if(bis_closeFlag) {
			bis.close();
		}
		os.flush();
		os.close();
	}
	/**
	 * 读取文件同时写回
	 * @param fileUrl
	 * @param response
	 * @throws IOException
	 */
	public static void readNetFileAndWirte(String fileUrl,boolean bis_closeFlag,String fileName,HttpServletResponse response) throws IOException {
		writeFile(readFileFromNet(fileUrl), true,fileName,response);
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值