根据url获取文件流MultipartFile

常见的url包含网络上一些图片的链接,静态服务器上边的图片地址等等,有时候一些链接内嵌到自己项目中时,由于图片大小或者网站的一些防盗处理,往往无法正确加载图片,因此需要单独做处理;

1.pom文件添加

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

2.详细代码

public MultipartFile createFileItem(String url) throws Exception{
        FileItem item = null;
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setReadTimeout(30000);
        conn.setConnectTimeout(30000);

        // 设置应用程序要从网络连接读取数据
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        String fileName = "";

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream();
            //获取文件名称
            String newUrl = conn.getURL().getFile();
            if (newUrl != null || newUrl.length() <= 0) {
                newUrl = java.net.URLDecoder.decode(newUrl, "UTF-8");
                int pos = newUrl.indexOf('?');
                if (pos > 0) {
                    newUrl = newUrl.substring(0, pos);
                }
                pos = newUrl.lastIndexOf('/');
                fileName = newUrl.substring(pos + 1);
            }
            //此处获取两次,是因为如果只获取一次的话,获取type类型时,文件大小会损坏变小,所以重新获取一次
            BufferedInputStream bis = null;
            HttpURLConnection conn1 = (HttpURLConnection) new URL(url).openConnection();
            bis = new BufferedInputStream(conn1.getInputStream());
            String type = HttpURLConnection.guessContentTypeFromStream(bis);

            FileItemFactory factory = new DiskFileItemFactory(16, null);
            String textFieldName = "downloadFile";  //此处任务取值
            if(!fileName.contains(".") && type != null){
                fileName = fileName + "." + FileUtils.getFileType(type);
            }
            logger.info("文件名为:" + fileName + "  大小" + (conn.getContentLength()/1024)+"KB" + "   contentType=" + type);
            item = factory.createItem(textFieldName, type, false, fileName);
            OutputStream os = item.getOutputStream();

            int bytesRead;
            byte[] buffer = new byte[1024 * conn.getContentLength()];
            while ((bytesRead = is.read(buffer, 0, buffer.length)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            is.close();
        }

        if (item != null) {
            return new CommonsMultipartFile(item);
        }
        return null;
    }

3.工具类

/**
     * 根据content-type获取文件后缀
     * @param fileContentType
     * @return
     */
    public static String getFileType(String fileContentType){
        switch (fileContentType) {
            case "image/tiff": return "tif";
            case "image/fax": return "fax";
            case "image/gif": return "gif";
            case "image/jpeg": return "jpg";
            case "image/png": return "png";
            case "image/vnd.wap.wbmp": return "wbmp";
            case "audio/x-wav": return "webp";

            default: return "jpg";
        }
    }

在网上查了一些资料,都不是很详细,因此整理一下方便以后使用,可以根据上述代码获取url文件名,文件后缀,文件大小等。

注:如果url中文件自带后缀名,如4.png之类的,是不需要使用上述工具类的,可以直接获取到。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,可以得出以下结论: 根据引用,在Spring MVC的Controller中,如果要接收MultipartFile类型的文件参数,需要使用@RequestParam注解来标识该参数。 根据引用,如果当前请求不是一个multipart请求,那么在尝试获取MultipartFile类型的文件参数时,会抛出MultipartException异常。 根据以上信息,可以得出以下答案: 在OSS中,无法直接根据URL获取MultipartFile类型的文件。因为MultipartFile是Spring MVC框架中的一种特殊类型,它用于接收上传的文件数据。而URL只是一个文件的地址,无法直接转换为MultipartFile类型。 如果你想要将OSS中的文件转换为MultipartFile类型,你需要先将文件下载到本地,然后再将本地文件转换为MultipartFile类型。你可以使用Java的IO来实现文件的下载和转换。 以下是一个示例代码,演示了如何根据URL获取OSS文件并将其转换为MultipartFile类型: ```java import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import java.io.*; import java.net.URL; public class OSSUtils { public static MultipartFile getMultipartFileFromUrl(String url) throws IOException { // 下载文件到本地 URL fileUrl = new URL(url); InputStream inputStream = fileUrl.openStream(); File tempFile = File.createTempFile("temp", null); FileOutputStream outputStream = new FileOutputStream(tempFile); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); // 将本地文件转换为MultipartFile类型 FileInputStream fileInputStream = new FileInputStream(tempFile); MultipartFile multipartFile = new CommonsMultipartFile(fileInputStream); // 删除临时文件 tempFile.delete(); return multipartFile; } } ``` 请注意,上述代码中使用了CommonsMultipartFile类来创建MultipartFile对象。如果你使用的是Spring Boot 2.0及以上版本,可以直接使用StandardMultipartFile类。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值