java-通过url下载文件到服务器指定目录

1. 使用场景,某个文件服务器里面保存了某个图片或者pdf文件,通过url的形式传输到自己这边,然后需要将url承载的文件保存到自己的电脑(服务器)里面。

2. 如果url自带文件名或者文件名加文件后缀那就是最方便的,获取文件名和后缀的时候就从urlAddress.substring来获取,反之这里工具用的是url不带文件名和后缀,需要自己传入destinationDir,并且我这里将文件后缀名字写死了.jpg,可以写一个灵活的后缀

3. 工具类的入口是fileDownload方法urlAddress大致长成"http://www.baidu.com/xxxxxxx"

destinationDir大致为"/User/file/xxx.jpg"

4.工具是灵活的传入的参数也是灵活的,可根据自己的需要修改

@UtilityClass
@Slf4j
public class FileUtil {

    /**
     * SIZE
     */
    private final int size = 1024;

    /**
     * File url
     *
     * @param urlAddress url address
     * @param localFileName local file name
     * @param destinationDir destination dir
     */
    public static void fileUrl(String urlAddress, String localFileName, String destinationDir) {
        OutputStream outputStream = null;
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(urlAddress);
            outputStream = new BufferedOutputStream(Files.newOutputStream(Paths.get(destinationDir + "\\" + localFileName + ".jpg")));
            urlConnection = url.openConnection();
            inputStream = urlConnection.getInputStream();

            byte[] buf = new byte[size];
            int byteRead, byteWritten = 0;
            while ((byteRead = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, byteRead);
                outputStream.flush();
                byteWritten += byteRead;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    /**
     * File download
     *
     * @param urlAddress url address
     * @param destinationDir destination dir
     */
    public static void fileDownload(String urlAddress, String destinationDir) {
        int slashIndex = destinationDir.lastIndexOf('/');
        int periodIndex = destinationDir.lastIndexOf('.');

        String fileName = destinationDir.substring(slashIndex + 1, periodIndex);

        if (periodIndex >= 1 && slashIndex >= 0 && slashIndex < urlAddress.length() - 1) {
            fileUrl(urlAddress, fileName, destinationDir);
        } else {
            System.err.println("path or file name.");
        }
    }
}

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用Java中的URLConnection类来实现文件上传。下面是一个简单的示例代码: ``` import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { public static void main(String[] args) { String serverUrl = "http://example.com/upload.php"; // 服务器上传接口地址 String filePath = "path/to/image.jpg"; // 本地文件路径 String serverPath = "/var/www/html/uploads/"; // 服务器目标路径 try { // 创建连接 URL url = new URL(serverUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------123821742118716"); connection.setRequestProperty("Content-Disposition", "form-data; name=\"file\"; filename=\"" + new File(filePath).getName() + "\""); // 读取文件并写入请求体 FileInputStream fileInputStream = new FileInputStream(new File(filePath)); OutputStream outputStream = connection.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } // 结束请求体 outputStream.flush(); outputStream.write("\r\n".getBytes()); outputStream.write("-----------------------------123821742118716--\r\n".getBytes()); // 发送请求并获取响应 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { System.out.println("文件上传成功!"); } else { System.out.println("文件上传失败,错误代码:" + responseCode); } // 关闭连接 fileInputStream.close(); outputStream.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们创建一个HTTP连接对象,并设置请求头部信息。然后,我们读取本地文件,将其写入请求体,再发送请求并获取响应。最后,我们关闭连接。请注意,这段代码只是一个示例,你需要根据自己的实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值