java URLConnection 实现文件上传

* 此工具类不建议上传大文件(百兆以上),大文件有内存溢出的风险。如果需要传大文件,可使用 hc 另行实现。
* 此工具类适用于普通网站中用户上传的图片、小附件等文件存储。

	public static HashMap upload(MultipartFile file, String domain, boolean isProtected){
		HashMap map = null;
		
		URI uri = URI.create("http://static.myechinese.com/up");
		InetSocketAddress sa = new InetSocketAddress("218.106.246.55", 80);
		Proxy proxy = new Proxy(Type.HTTP, sa);
		try {
			URLConnection conn = uri.toURL().openConnection(proxy);
			String boundary = "---------------------------" + System.currentTimeMillis();
			String boundaryInContent = "--" + boundary;
			String rn = "\r\n";
			conn.addRequestProperty("Connection", "keep-alive");
			conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(1000);
			conn.setUseCaches(false);
			conn.connect();
			OutputStream out = conn.getOutputStream();
			StringBuilder sb = new StringBuilder();
			sb.append(boundaryInContent).append(rn);
			sb.append("Content-Disposition: form-data; name=domain").append(rn).append(rn);
			sb.append(domain).append(rn);
			sb.append(boundaryInContent).append(rn);
			sb.append("Content-Disposition: form-data; name=isProtected").append(rn).append(rn);
			sb.append(isProtected).append(rn);
			sb.append(boundaryInContent).append(rn);
			sb.append("Content-Disposition: form-data; name=file; filename=" + file.getOriginalFilename()).append(rn);
			sb.append("Content-Type: " + file.getContentType()).append(rn).append(rn);
			out.write(sb.toString().getBytes());
			out.write(file.getBytes());
			sb.delete(0, sb.length());
			sb.append(rn).append(boundaryInContent).append("--").append(rn).append(rn);
			out.write(sb.toString().getBytes());
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String res = reader.readLine();
			reader.close();
			System.out.println("Uploader: " + res);
			map = new Gson().fromJson(res, HashMap.class);// Gson 有点坑,数字默认给转成 Double 类型
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return map;
	}

发表评论

电子邮件地址不会被公开。 必填项已用*标注