客户端上传/下载代码
package com.cqs.qicaiyun.system.net;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
/**
* 客户端实现文件上传 下载
* <p>
* create date: 18-7-21 10:43
*/
@Log4j2
public class UploadClient {
private final static String BOUNDARY_PREFIX = "--";
private final static String NEW_LINE = "\r\n";
//数据分割线
private final static String BOUNDARY = "----WebKitFormBoundaryVc5ISK3OrIupy3EZ";
public static void upload(String url, File[] files) {
if (files == null || files.length == 0) {
log.info("上传文件为空");
return;
}
//URL
URL url2 = null;
try {
url2 = new URL(url);
} catch (MalformedURLException e) {
throw new RuntimeException("打开URL失败:", e);
}
HttpURLConnection connection;
try {
connection = (HttpURLConnection) url2.openConnection();
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
//表单方式提交
connection.setRequestProperty("content-type", "multipart/form-data; BOUNDARY=" + BOUNDARY);
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
connection.setRequestProperty("Connection", "Keep-Alive");
// 设置字符编码
connection.setRequestProperty("Charset", "UTF-8");
long content_length = 100;
connection.setRequestProperty("Range", String.valueOf(content_length));
try (OutputStream os = connection.getOutputStream()) {
//向流中输出数据
//开始写入文件
int count = 0;
for (File file : files) {
//注意
StringBuilder start = new StringBuilder(NEW_LINE + BOUNDARY_PREFIX);
start.append(BOUNDARY);
start.append(NEW_LINE);
//TODO name可根据业务决定是否写死
String name = "qicaiyun" + (++count);
start.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"");
start.append(file.getName());
start.append("\"");
start.append(NEW_LINE);
start.append("Content-type: application/octet-stream");
//重要:注意这里是两个换行(其他地方是一个换行)
start.append(NEW_LINE);
start.append(NEW_LINE);
/**
------WebKitFormBoundaryVc5ISK3OrIupy3EZ
Content-Disposition: form-data; name="qicaiyun2"; filename="WebSocketClient.java"
Content-type: application/octet-stream
**/
log.debug("start:" + start.toString());
os.write(start.toString().getBytes());
os.flush();
//写入内容
byte[] buf = new byte[1024 * 512];
try (FileInputStream fis = new FileInputStream(file)) {
int len;
while ((len = fis.read(buf)) != -1) {
os.write(buf, 0, len);
content_length += len;
}
os.flush();
}
log.debug("写入文件{}到输出流", file.getName());
}
//上传文件结束
StringBuilder end = new StringBuilder(NEW_LINE + BOUNDARY_PREFIX);
end.append(BOUNDARY);
end.append("--");
end.append(NEW_LINE);
os.write(end.toString().getBytes());
/**
------WebKitFormBoundaryVc5ISK3OrIupy3EZ--
*/
log.debug("end:" + end);
os.flush();
}
//打印返回结果
try (InputStream is = connection.getInputStream()) {
if (is != null) {
byte[] bytes = new byte[is.available()];
is.read(bytes);
log.info("返回结果:"+new String(bytes));
is.close();
}
}
} catch (IOException e) {
throw new RuntimeException("打开" + url + "失败:" + e.getMessage());
}
}
/**
* 客户端实现文件下载
*
* @param url
*/
public static void download(String url) {
URL url2 = null;
try {
url2 = new URL(url);
} catch (MalformedURLException e) {
throw new RuntimeException("打开URL失败:", e);
}
try {
HttpURLConnection connection = (HttpURLConnection) url2.openConnection();
String field = connection.getHeaderField("Content-Disposition");
String fn = "filename=";
String fileName = "unknown";
if (StringUtils.isNotEmpty(field) && field.contains(fn)) {
fileName = field.substring(field.indexOf(fn));
}
FileOutputStream fos;
try (InputStream is = connection.getInputStream()) {
//输出的是文件类型
File file = new File(fileName);
fos = new FileOutputStream(file);
byte[] bytes = new byte[1024 * 512];
int len;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
}
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File[] files = {
new File("/home/li/IdeaProjects/qicaiyun/src/main/java/com/cqs/qicaiyun/system/net/websocket/PushDemo.java"),
new File("/home/li/IdeaProjects/qicaiyun/src/main/java/com/cqs/qicaiyun/system/net/websocket/WebSocketClient.java")
};
String url = "http://localhost:9090/qicaiyun/image/upload";
upload(url, files);
String url2 = "http://localhost:9090/qicaiyun/image/download";
download(url2);
}
}
服务端代码
@PostMapping("/upload")
public Result upload(HttpServletRequest request) {
try {
Collection<Part> parts = request.getParts();
if (parts != null) {
byte[] buf = new byte[1024 * 512];
parts.stream().filter(part -> !part.getName().startsWith("qicaiyun"))
.forEach(part -> {
try (InputStream is = part.getInputStream()) {
String name = part.getSubmittedFileName();
// log.debug("name:" + name);
File file = new File(name);
int len;
try (FileOutputStream fos = new FileOutputStream(file)) {
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
}
log.info("上传文件{}成功", name);
} catch (IOException e) {
e.printStackTrace();
}
});
}
} catch (IOException | ServletException e) {
return FailedResult.build().reason(e.getMessage());
}
return SuccessResult.build().result("SUCCESS");
}
//文件下载
@GetMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response) {
//下载文件路径 -- demo
File file = new File("/home/li/Documents/sublime_text_3_build_3176_x64.tar.bz2");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
try (FileInputStream fis = new FileInputStream(file)) {
//
try (ServletOutputStream os = response.getOutputStream()) {
int len;
byte[] download = new byte[1024 * 512];
while ((len = fis.read(download)) != -1) {
os.write(download, 0, len);
}
os.flush();
}
response.setContentLengthLong(file.length());
} catch (IOException e) {
e.printStackTrace();
}
}