服务端接收大文件步骤(Spring框架)
- pom文件引入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
- springMVC配置文件增加如下配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
- Controller层接收参数类型
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Result upload(@RequestParam("file") MultipartFile file) {
return Result.create(service.file(file));
}
服务端将文件上传到远程服务器
- 远程服务接收文件为file格式
/**
* 上传文件到远程服务器
* @param url 远程服务接口地址
* @param file 源文件
* @param fileParamName 远程服务接收文件参数名
* @return string 网络可访问的文件地址
*/
public staic String uploadFile(String url, MultipartFile file, String fileParamName) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
String fileName = file.getOriginalFilename();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
//加上此行代码解决返回中文乱码问题
builder.setMode(HttpMultipartMode.RFC6532);
// 文件流
builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 执行提交
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
2.远程服务接收文件为流格式
/**
* 上传inputStream到远程服务器
* @param url 远程服务接口地址
* @param stream 流文件
* @param fileName 文件名称
* @return
*/
public static String uploadInputStream(String url, InputStream stream, String fileName) {
CloseableHttpResponse execute = null;
String result = "";
try {
HttpPost post = new HttpPost(url + fileName);
post.setEntity(new ByteArrayEntity(IOUtils.toByteArray(stream)));
CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
execute = closeableHttpClient.execute(post);
result = EntityUtils.toString(execute.getEntity());
JSONObject object = JSONObject.parseObject(result);
result = object.getString("result");
return result;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
附:业务中经常使用文件处理上传,建议将方法写在一个工具类中,且用static修饰,则业务中有需要用到的地方可以直接通过类调用此方法(类.方法名)。