TestFile.java
package com.test;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestFile {
/**
* @param args
*/
public static void main(String[] args)
{
// String photoUrl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1598446136883&di=914d49a65244f4eb87ad2e0be5bca3cf&imgtype=0&src=http%3A%2F%2Fa3.att.hudong.com%2F14%2F75%2F01300000164186121366756803686.jpg"; //文件URL地址
String photoUrl = "http://www.screnhe.gov.cn/uploadfiles/201911/27/2019112717091384521260.zip"; //文件URL地址
System.out.println(photoUrl.substring(photoUrl.lastIndexOf(".")));
String fileName = "123"; //为下载的文件命名
String filePath = "d:"; //保存目录
File file = saveUrlAs(photoUrl, filePath + fileName);
}
/**
* @从制定URL下载文件并保存到指定目录
* @param filePath 文件将要保存的目录
* @param url 请求的路径
* @return
*/
public static File saveUrlAs(String url,String filePath){
// filePath = "d:\\123";//保存目录
System.out.println("fileName---->"+filePath);
//创建不同的文件夹目录
File file=new File(filePath);
//判断文件夹是否存在
if (!file.exists())
{
//如果文件夹不存在,则创建新的的文件夹
file.mkdirs();
}
FileOutputStream fileOut = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try
{
// 建立链接
URL httpUrl=new URL(url);
conn=(HttpURLConnection) httpUrl.openConnection();
//以Post方式提交表单,默认get方式
//conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
// post方式不能使用缓存
conn.setUseCaches(false);
//连接指定的资源
conn.connect();
//获取网络输入流
inputStream=conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
//判断文件的保存路径后面是否以/结尾
if (!filePath.endsWith("/")) {
filePath += "/";
}
//写入到文件(注意文件保存路径的后面一定要加上文件的名称)
fileOut = new FileOutputStream(filePath + System.currentTimeMillis() + url.substring(url.lastIndexOf(".")));
BufferedOutputStream bos = new BufferedOutputStream(fileOut);
byte[] buf = new byte[4096];
int length = bis.read(buf);
//保存文件
while(length != -1)
{
bos.write(buf, 0, length);
length = bis.read(buf);
}
bos.close();
bis.close();
conn.disconnect();
} catch (Exception e)
{
e.printStackTrace();
System.out.println("下载错误,抛出异常!!");
}
return file;
}
}
接口 FileController.java
package com.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File;
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping(value = "/download")
public void fileDownLoad(@RequestParam("url") String url, @RequestParam("filePath")String filePath){
File file = TestFile.saveUrlAs(url, filePath);
if (file!= null){
System.out.println("文件下载成功!");
}
}
}
测试:
在 postman 中测试接口:
http://127.0.0.1:8097/file/download2?url=http://www.screnhe.gov.cn/uploadfiles/201911/27/2019112717091384521260.zip&filePath=d:123
结果如下: