public static String sendFile(final String url, byte[] file, String filename) throws Exception{
final String boundary = "===" + Long.toHexString(System.currentTimeMillis()) + "===";//分割线
final String CRLF = "\r\n";
HttpURLConnection httpConn = null;
try {
httpConn = (HttpURLConnection) new URL(url).openConnection();
httpConn.setConnectTimeout(5 * 1000);
httpConn.setRequestProperty("Connection", "close");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setUseCaches(false);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpConn.connect();
try (
OutputStream output = httpConn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true)
) {
writer.append("--" + boundary)
.append(CRLF)
.append("Content-Disposition: form-data; name=file; filename=" + filename)
.append(CRLF)
.append(
new StringBuilder("Content-Type:")
.append( URLConnection.guessContentTypeFromName(filename) )
.append("; charset=UTF-8")
)
.append(CRLF)
.append("Content-Transfer-Encoding: binary")
.append(CRLF)
.append(CRLF)
.flush();
output.write(file);
output.flush();
writer.append(CRLF)
.flush();
writer.append("--" + boundary + "--")
.append(CRLF)
.flush();
//http1.1是半双工模式,必须写完成之后再拿服务端的inputStream
try (InputStream inputStream = httpConn.getInputStream()){
byte[] resByte = new byte[ inputStream.available() ];
inputStream.read(resByte);
String res = new String(resByte);
System.out.println(res);
return res;
}
}
} finally {
if (httpConn != null){
httpConn.disconnect();
}
}
}
main方法进行测试:
public static void main(String[] args) throws Exception {
FileChannel fileChannel = FileChannel.open( Paths.get("B:\\documents\\mycat.pdf") );
ByteBuffer byteBuffer = ByteBuffer.allocate( (int) fileChannel.size() );
fileChannel.read(byteBuffer);
sendFile("http://localhost:8097/api/save", byteBuffer.array(), "mycat-pdf");
}
springmvc后端接口接收:
@RequestMapping(value = "/save", method = RequestMethod.POST)
public LllFile save(@RequestParam(name = "file") MultipartFile multipartFile, String filename, String usrId, String acct){
try{
byte[] file = multipartFile.getBytes();
LllFile res = iFileService.saveFile(file, filename, usrId, acct);
return res;
}catch(Exception ex){
log.error("", ex);
}
return null;
}
纯servlet接收,通过request的getPart方法:
@RequestMapping(value = "/save", method = RequestMethod.POST)
public LllFile save(HttpServletRequest request) throws IOException, ServletException {
Collection<Part> parts = request.getParts();
for (Part part : parts) {
System.out.println(part.getSize());
System.out.println("文件名:" + part.getSubmittedFileName());
}
return null;
}
上传多个文件:
1:首先查看浏览器是怎么区分多文件的;
-----Webkit***是chrome用来区分文件的,最后一个boundary后面多了个--。
java实现如下:
public static String sendMultipleFile(Map<String, byte[]> fileMsgMap, final String url) throws Exception {
final String boundary = "===" + Long.toHexString(System.currentTimeMillis()) + "===";//分割线
final String CRLF = "\r\n";
HttpURLConnection httpConn = null;
try {
httpConn = (HttpURLConnection) new URL(url).openConnection();
httpConn.setConnectTimeout(5 * 1000);
httpConn.setRequestProperty("Connection", "close");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setUseCaches(false);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpConn.connect();
try (
OutputStream output = httpConn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true)
) {
for (Map.Entry<String, byte[]> entry : fileMsgMap.entrySet()) {
writer.append("--" + boundary)
.append(CRLF)
.append("Content-Disposition: form-data; name=files; filename=" + entry.getKey())
.append(CRLF)
.append(
new StringBuilder("Content-Type:")
.append( URLConnection.guessContentTypeFromName(entry.getKey()) )
.append("; charset=UTF-8")
)
.append(CRLF)
.append("Content-Transfer-Encoding: binary")
.append(CRLF)
.append(CRLF)
.flush();
output.write(entry.getValue());
output.flush();
writer.append(CRLF)
.flush();
}
//最后一行末尾多个--
writer.append("--" + boundary + "--")
.append(CRLF)
.flush();
//http1.1是半双工模式,必须写完成之后再拿服务端的inputStream
try (InputStream inputStream = httpConn.getInputStream()){
byte[] resByte = new byte[ inputStream.available() ];
inputStream.read(resByte);
String res = new String(resByte);
System.out.println(res);
return res;
}
}
} finally {
if (httpConn != null){
httpConn.disconnect();
}
}
}
springmvc接收代码:
@PostMapping(path = "/up")
@ResponseBody
public String upFile(@RequestParam(name = "files") MultipartFile[] multipartFiles, HttpServletRequest request) throws IOException, ServletException {
// Collection<Part> parts = request.getParts();
// for (Part part : parts) {
// System.out.println(part.getSize());
// System.out.println("文件名:" + part.getSubmittedFileName());
// }
System.out.println(multipartFiles);
System.out.println(multipartFiles.length);
for (MultipartFile file : multipartFiles) {
System.out.println("文件名是:" + file.getOriginalFilename());
System.out.println("文件信息大小是:" + file.getBytes().length);
}
return "ok";
}
上传多个文件最好修改tomcat的最大post请求大小限制,
server:
tomcat:
max-http-form-post-size: 40MB
或者
server:
tomcat:
#30Mb最大post请求体
max-http-post-size: 31457280