Java URL转File,URL转MultipartFile

如果只需要转File,无需导入maven

<!-- 转MultipartFile才需要导这个maven包 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
</dependency>
import java.io.*;
import java.net.URL;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
// url: 链接,可访问的图片,视频,或其他文件
public MultipartFile urlTransferMultipartFile(String url){
    //对本地文件命名,可以从链接截取,可以自己手写,看需求
    String fileName = "img_test"
    // String fileName = url.substring(url.lastIndexOf("."));
    File file = null;
    URL urlfile;
    InputStream inStream = null;
    OutputStream os = null;
    MultipartFile multipartFile = null;
    try {
        file = File.createTempFile("net_url", fileName);
        //下载
        urlfile = new URL(url);
        inStream = urlfile.openStream();
        os = new FileOutputStream(file);

        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        // file转multipartFile,如果只需要转File就不用加下面这两行代码,直接返回File即可
        FileInputStream inputStream = new FileInputStream(file);
        multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != os) {
                os.close();
            }
            if (null != inStream) {
                inStream.close();
            }
            // 用完删除
            if (null != file){
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 按需返回file还是multipartFile
    return multipartFile;
}
  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XFly.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值