java http上传接收文件

commons-httpclient commons-httpclient 3.1
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.10</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.2.2.RELEASE</version>
    </dependency>

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

public class FileLoadClient {
	
	private static final int TIMEOUT = 5000;
	
	public static void main(String[] args) {
		fileload("http://localhost:8080/uploadFile", new File("D:\\google-collections\\1.0\\google-collections-1.0.jar"));
	}
	
	public static String fileload(String url, File file) {
		String body = "{}";
		
		if (url == null || url.equals("")) {
			return "illegal";
		}
		if (!file.exists()) {
			return "file not exist";
		}
		
		PostMethod postMethod = new PostMethod(url);
		BufferedReader br = null;
		try {
			// FilePart:用来上传文件的类,file即要上传的文件
			FilePart fp = new FilePart("file", file);
			Part[] parts = {fp};
			
			// 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
			MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
			postMethod.setRequestEntity(mre);
			
			HttpClient client = new HttpClient();
			// 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间
			client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT);
			int status = client.executeMethod(postMethod);
			if (status == HttpStatus.SC_OK) {
				InputStream inputStream = postMethod.getResponseBodyAsStream();
				br = new BufferedReader(new InputStreamReader(inputStream));
				StringBuffer stringBuffer = new StringBuffer();
				String str = "";
				while ((str = br.readLine()) != null) {
					stringBuffer.append(str);
				}
				body = stringBuffer.toString();
			} else {
				body = "fail";
			}
		} catch (Exception e) {
//            。。。
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
//					。。。
				}
			// 释放连接
			postMethod.releaseConnection();
		}
		return body;
	}
}


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class UploadFile {
	
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public String uploadFile(HttpServletResponse response, @RequestParam("file") MultipartFile file) {
		if (file != null && !file.isEmpty()) {
			try {
				String filePath = file.getOriginalFilename();
				InputStream inputStream = null;
				FileOutputStream outputStream = null;
				try {
					inputStream = file.getInputStream();
					File f = new File(filePath);
					f.createNewFile();
					byte[] bom = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
					outputStream = new FileOutputStream(f);
					if (filePath.endsWith(".txt")) {
						outputStream.write(bom);//写入BOM头
					}
					byte temp[] = new byte[1024];
					int size = -1;
					while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB,直至读完
						outputStream.write(temp, 0, size);
					}
					response.getWriter().write("upload success");
				} catch (IOException e) {
					return e.getMessage();
				} finally {
					outputStream.close();
					inputStream.close();
				}
			} catch (Exception e) {
				return e.getMessage();
			}
		}
		return "File is Empty";
	}
	
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值