【java字节数组转换MultipartFile】

该代码示例展示了如何从URL下载图片,将其转换为字节数组,进一步封装成MultipartFile对象,然后使用FastDFS服务进行上传。关键步骤包括设置HTTP连接参数,读取输入流,转换成字节数组,以及通过FastDFS接口上传文件。
摘要由CSDN通过智能技术生成

1.将字节数组转换MultipartFile上传对象

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-mock</artifactId>
    <version>2.0.8</version>
</dependency>

2.具体方法

public String getZxPictureNameNew2(String pictureLinkUrl,String fileName) {
        log.info("start download ! pictureLinkUrl:{}", pictureLinkUrl);
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        String uploadUrl = "";
        try {
            // 统一资源
            URL url = new URL(pictureLinkUrl);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000 * 5);
            //设置请求方式,默认是GET
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();
            //获取原始文件名
//            String fileName = pictureLinkUrl.substring(pictureLinkUrl.lastIndexOf("/") + 1)+".png";
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int size = 0;
            byte[] buf = new byte[2048];
            while ((size = bin.read(buf)) != -1) {
                bos.write(buf, 0, size);
            }
            byte[] bytes = bos.toByteArray();
// 字节数组转MultipartFile !!!!!
            InputStream inputStream2 = new ByteArrayInputStream(bytes);
            MultipartFile multipartFile = new MockMultipartFile("__init__.py", fileName, "application/octet-stream", inputStream2);

            uploadUrl = fastDfsService.upload(multipartFile, "super");

        } catch (Exception e) {
            log.error("下载第三方资讯图链接错误,======{}", e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception e) {
                log.error("close inputStream error===={}", e);
            }
        }
        return uploadUrl;
    }

3.上传接口

  public String upload(MultipartFile file, String uploadName) throws IOException {
        HttpHeaders fileHeader = new HttpHeaders();
        fileHeader.setContentType(MediaType.parseMediaType(Objects.requireNonNull(file.getContentType())));
        fileHeader.setContentDispositionFormData("file", file.getOriginalFilename());

        HttpEntity<ByteArrayResource> fileEntity = new HttpEntity<>(new ByteArrayResource(file.getBytes()), fileHeader);
        HttpHeaders headers = this.getBaseHeaders();
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.set("file", fileEntity);
        JSONObject resultVo = RestTemplateUtils.remoteForm(headers, paramMap, this.getCdnUploadUrl(uploadName), JSONObject.class);
        Assert.isFalse(resultVo.getInteger("errorCode") != CommonConstant.SUCCESS_CODE, String.format("上传文件失败,%s", resultVo.getString("errorInfo")));
        return resultVo.getString("data");
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值