服务器之间的文件上传下载

编程

 public static GifResultDto uploadToGift(MultipartFile file, String suffix) {

String url = new StringBuilder(GIFT_FILE_UPLOAD_URL).append(GIFT_FILE_NAMESPACE).append("/").append(getImgFlag(suffix)).toString();

LOGGER.info("上传文件链接:" + url);

String result = "";

GifResultDto gifResultDto = new GifResultDto();

try (CloseableHttpClient client = HttpClients.createDefault()) {

HttpPost httpPost = new HttpPost(url);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

builder.addBinaryBody("filecontent", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, new String(file.getOriginalFilename().getBytes("ISO-8859-1"), "UTF-8"));

HttpEntity httpEntity = builder.build();

httpPost.setEntity(httpEntity);

try (CloseableHttpResponse response = client.execute(httpPost)) {

HttpEntity responseEntity = response.getEntity();

if (responseEntity != null) { // 将响应内容转换为字符串

result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));

LOGGER.info("上传文件返回结果:{}", result);

gifResultDto = BeanJsonConversionUtil.jsonConversionBean(result, GifResultDto.class);

if (gifResultDto == null || gifResultDto.getStatusCode() == null || gifResultDto.getStatusCode() != 200) {

throw new RuntimeException(result);

}

}

}

} catch (Exception e) {

throw new RuntimeException("上传文件异常:", e);

}

return gifResultDto;

}

下载

public static byte[] downLoadFromGift(String type) throws Exception {

String url = new StringBuilder(GIFT_FILE_DOWNLOAD_URL).append(GIFT_FILE_NAMESPACE).append("/").append(type).toString();

LOGGER.info("下载文件链接:" + url);

File desc = getFileByType(type);

byte[] result;

try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

HttpGet httpget = new HttpGet(url);

httpget.setConfig(RequestConfig.custom().build());

try (CloseableHttpResponse response = httpclient.execute(httpget)) {

HttpEntity entity = response.getEntity();

File folder = desc.getParentFile();

folder.mkdirs();

try (InputStream is = entity.getContent();

ByteArrayOutputStream os = new ByteArrayOutputStream()) {

StreamUtils.copy(is, os);

result = os.toByteArray();

}

} catch (Exception e) {

throw new RuntimeException("文件下载失败......", e);

}

}

return result;

}

 

以上是 服务器之间的文件上传下载 的全部内容, 来源链接: utcz.com/z/516134.html

回到顶部