Java编写接口,实现根据地址下载文件到指定文件夹

本文介绍如何使用Java编写一个接口FileController.java,该接口能从给定的URL下载文件并保存到用户指定的文件夹。通过TestFile.java进行测试,并在Postman中调用接口http://127.0.0.1:8097/file/download2进行验证,成功实现了文件的下载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

结果如下:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值