JAVA后台模拟文件上传

关于网上前端上传文件的已经烂大街了,这里主要描述后台模拟文件上传的具体实现,记录一下踩坑。

使用场景主要是公司内部项目后端定时上传日志文件到管理平台,废话不多说,上代码:

  1. 首先插入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” 获取到此文件流对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值