【JAVA】从URL下载文件到本地的工具类

package utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

/**
 * @author passerbyYSQ
 * @create 2020年3月26日 下午11:24:29
 */
public class DownloadHelper {
	
	private static int timeout = 3000;
	/*
	public static void main(String[] args) {
		//String urlStr = "https://img-blog.csdnimg.cn/20200228105746752.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjkwMzE4,size_16,color_FFFFFF,t_70";
		//String urlStr = "https://salary-management.oss-cn-shenzhen.aliyuncs.com/img/photo/233.jpg";
		//String urlStr = "https://dldir1.qq.com/qqyy/pc/QQPlayerSetup4.6.2.1089.exe";
		String urlStr = "https://moodle.scnu.edu.cn/pluginfile.php/521241/mod_resource/content/0/%E7%AC%AC4%E5%91%A8%20%E8%AF%BE%E5%A0%82%E7%BB%83%E4%B9%A0.pptx";
		String savePath = "C:\\Users\\Administrator\\Desktop";
		try {
			System.out.println("开始下载...");
			Long sta = System.currentTimeMillis();
			boolean res = downloadFromUrl(urlStr, savePath);
			Long end = System.currentTimeMillis();
			if (res) {
				System.out.println("下载成功!!!");
			} else {
				System.out.println("下载失败!!!");
			}
			System.out.println("耗时:" + (end - sta) + " ms");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	*/
	
	/**
	 * @param urlStr
	 * @param savePath
	 * @return
	 * @throws IOException
	 */
	public static boolean downloadFromUrl(URL url, String savePath) throws IOException {
		File destDir = new File(savePath);
		// 如果保存的目录不存在,则创建
		if (!destDir.isDirectory()) {
			destDir.mkdirs();
		}
		
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(timeout);
		// 获取文件名
		String fileName = getFileName(conn);
		if (fileName == null) {
			return false;
		}
		
		//防止屏蔽程序抓取而返回403错误
        //conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		
        // 输入流
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
		
        File destFile = new File(destDir, fileName);
        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        
        byte[] buf = new byte[1024];
        int len;
        while ((len = bis.read(buf)) != -1) {
        	bos.write(buf, 0, len);
        }
        
        // 关闭外层流,内层的流也会自动地关闭
        close(bos, bis);
		return true;
	}
	
	/**
	 * 返回下载的文件名
	 * @param urlStr
	 * @param savePath
	 * @return
	 * @throws IOException
	 */
	public static boolean downloadFromUrl(String urlStr, String savePath) throws IOException {
		return downloadFromUrl(new URL(urlStr), savePath);
	}
	
	public static String getFileName(HttpURLConnection conn) {
		String fileName = getFileName1(conn);
		if (fileName != null) {
			//System.out.println("方式一");
			return fileName;
		}
		fileName = getFileName2(conn);
		//System.out.println("方式二");
		return fileName;
	}
	
	private static String getFileName2(HttpURLConnection conn) {
		String raw = conn.getHeaderField("Content-Disposition");  
		//System.out.println("raw: " + raw);
		if (raw != null && raw.indexOf("=") > 0) {            
			String fileName = raw.split("=")[1];            
			try {
				return URLDecoder.decode(fileName, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} 
		}
		return null;
	}
	
	private static String getFileName1(HttpURLConnection conn) {
		String newUrl = conn.getURL().getFile();  
		//System.out.println("newUrl: " + newUrl);
		if (newUrl != null && newUrl.length() > 0) { 
			try {
				newUrl = URLDecoder.decode(newUrl, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}    
			int pos = newUrl.indexOf('?');            
			if (pos >= 0) {                
				newUrl = newUrl.substring(0, pos);            
			}        
			pos = newUrl.lastIndexOf('/');            
			return newUrl.substring(pos + 1);        
		}
		return null;
	}
	
	public static void close(Closeable... closeables) {
        if (closeables == null)
            return;
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个Java本地测试文件上传的工具类示例: ```java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { private static final String LINE_FEED = "\r\n"; private final String boundary; private HttpURLConnection httpConn; private final String charset; public FileUploader(String requestURL, String charset) throws IOException { this.charset = charset; // creates a unique boundary based on time stamp boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates that we want to write to the HTTP request body httpConn.setDoInput(true); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); } public void addFilePart(String fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); StringBuilder sb = new StringBuilder(); sb.append("--").append(boundary).append(LINE_FEED); sb.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"" + LINE_FEED); sb.append("Content-Type: " + "application/octet-stream" + LINE_FEED); sb.append(LINE_FEED); byte[] headerBytes = sb.toString().getBytes(charset); byte[] trailerBytes = (LINE_FEED + "--" + boundary + "--" + LINE_FEED).getBytes(charset); httpConn.setRequestProperty("Content-Length", String.valueOf(headerBytes.length + uploadFile.length() + trailerBytes.length)); httpConn.getOutputStream().write(headerBytes); try (InputStream inputStream = uploadFile.toURI().toURL().openStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { httpConn.getOutputStream().write(buffer, 0, bytesRead); } httpConn.getOutputStream().write(trailerBytes); } } public int finish() throws IOException { int status = httpConn.getResponseCode(); httpConn.disconnect(); return status; } } ``` 使用示例: ```java public static void main(String[] args) throws IOException { String charset = "UTF-8"; String requestURL = "http://localhost:8080/upload"; FileUploader fileUploader = new FileUploader(requestURL, charset); File uploadFile = new File("path/to/local/file"); fileUploader.addFilePart("file", uploadFile); int status = fileUploader.finish(); System.out.println("Server response code: " + status); } ``` 其中,`requestURL`是文件上传接口的URL,`uploadFile`是要上传的本地文件。你需要将它们替换为你自己的URL文件路径。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值