天天看點

SpringBoot下如何将 byte[] 位元組檔案上傳到伺服器

分享知識 傳遞快樂

在 SpringBoot 下通過把取到的 byte[] 位元組檔案上傳到伺服器。實作如下:

byte[]流上傳服務

import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;


public class UploadUtils {

    private String upload(byte[] bytes, String fileName) {
        try {
            // 數組轉輸入流
            InputStream inputStream = new ByteArrayInputStream(bytes);
            // 輸入流轉MultipartFile對象
            MultipartFile multipartFile = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
            // 把MultipartFile這個對象轉成輸入流資源(InputStreamResource)
            InputStreamResource isr = new InputStreamResource(multipartFile.getInputStream(), fileName);
            log.info("upload file name : " + fileName);

            Map<String, Object> map = new HashMap<>();
            map.put("file", isr);

            HttpResponse execute = HttpRequest.post("url")
                    .contentType("multipart/form-data")
                    .form(map)
                    .execute();

            if (execute.getStatus() == 200) {
                JSONObject jsonObject = JSONUtil.parseObj(execute.body());
                if (jsonObject.getInt("errcode") == 200 && jsonObject.getJSONObject("datas") != null) {
                    return jsonObject.getJSONObject("datas").getStr("url");
                }
            }
        } catch (Exception e) {
            log.error("上傳檔案失敗", e);
        }
        return null;
    }

}      
@PostMapping("/upload/{appName}")
public Result upload(String appName, MultipartFile file) {

  return minIoBiz.upload(appName, file);
}