关于网上前端上传文件的已经烂大街了,这里主要描述后台模拟文件上传的具体实现,记录一下踩坑。
使用场景主要是公司内部项目后端定时上传日志文件到管理平台,废话不多说,上代码:
-
首先插入pom.xml 依赖 HTTP全家桶
<!-- HTTP -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
public class FileUpload {
private static Logger logger = LoggerFactory.getLogger(FileUpload.class);
public int upload(String file,String url,String nodeIp){
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
int code = 0 ;
try {
httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
HttpEntity data = getMultiDefaultFileEntity(file,nodeIp);
post.setEntity(data);
response = httpclient.execute(post);
code = response.getStatusLine().getStatusCode();
} catch (Exception e) {
logger.error("上传日志文件失败{},Cause by:{}",file,e.getMessage());
return UploadStatus.Exception;
} finally {
try {
if (response != null) response.close();
if (httpclient != null) httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return code ;
}
/**
* File文件格式上传(缺省)
*/
public HttpEntity getMultiDefaultFileEntity(String path,String ip) {
File file = new File(path);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.RFC6532); //以浏览器兼容方式 防止文字乱码
builder.addBinaryBody("file", file);
builder.addTextBody("ipAddress", ip);
// builder.setCharset(Charset.forName("utf-8"));
return builder.build();
}
踩坑:这里builder.setMode(HttpMultipartMode.RFC6532) 并非一定要设置此模式,如果上传文件名包含中文的话,设置成RFC6532可防止文件名乱码 ,builder.addBinaryBody("file", file)这里设置 类似前端 <input type='file' /> 对应的接收端可通过属性名“file” 获取到此文件流对象。