1.说明
公司用spring boot写了文件上传的接口,现方案那边需要提供个Java代码调用后台接口实现多文件上传。
1.1后台代码
@RequestMapping(value = "uploadMoreFile", method = RequestMethod.POST)
public Map<String, Object> uploadMoreFile(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) {
// 判断是否为空文件
if (file.length<1) {
RuntimeFileException exception = new RuntimeFileException(FileErrorCode.MULTIPARTFILE_IS_EMPTY, "上传文件不能为空!");
logger.error(exception.getMessage(), exception);
throw exception;
}
String destDir = request.getParameter(DESTINATION_DIR);
String isAbsolutePathStr = request.getParameter(IS_ABSOLUTE_PATH);
if (destDir==null){
destDir = File.separator+"workspace";
}
if (isAbsolutePathStr==null){
isAbsolutePathStr = "false";
}
boolean isAbsolutePath = !"false".equalsIgnoreCase(isAbsolutePathStr);
if (!isAbsolutePath) {
destDir = new File(CommonUtils.getApplicationDirectory(), destDir).getAbsolutePath();
}
logger.info("上传的文件路径为:" + destDir);
if (CommonUtils.isEmpty(destDir)) {
RuntimeFileException exception = new RuntimeFileException(FileErrorCode.DEST_DIR_IS_EMPTY, "文件上传目标位置不能为空!");
logger.error(exception.getMessage(), exception);
throw exception;
}
for (MultipartFile multipartFile : file) {
// 文件类型
String contentType = multipartFile.getContentType();
// 原文件名即上传的文件名
String origFileName = multipartFile.getOriginalFilename();
// 文件大小
Long fileSize = multipartFile.getSize();
// 保存文件
try {
if (!destDir.endsWith("/")) {
destDir = destDir + File.separator;
}
String target = destDir + origFileName;
File targetFile = new File(target);
if (targetFile.exists()) {
RuntimeFileException exception = new RuntimeFileException(FileErrorCode.TARGET_FILE_EXIST
, "要上传的文件[" + origFileName + "]已经存在!");
logger.warn(exception.getMessage());
throw exception;
}
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
multipartFile.transferTo(targetFile);
String msg = String.format(
file.getClass().getName() + "方式文件上传成功!\n文件名:%s,文件类型:%s,文件大小:%s Bytes", origFileName,
contentType, fileSize);
logger.info(msg);
} catch (IllegalStateException | IOException e) {
RuntimeFileException exception = new RuntimeFileException(FileErrorCode.FILE_EXCEPTION
, "文件上传失败!", e);
logger.error(exception.getMessage(), exception);
throw exception;
}
}
return packResult(FileErrorCode.SUCCESS_CODE.getCode(), "文件上传成功");
}
2.前端代码实现
忽略、、、
3.java代码实现
HttpClient使用MultipartEntityBuilder实现多文件上传
3.1 引入jar包
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpmime:4.5'
3.2 代码实现1
package cn.com.agree.ab.a5.client.gui.aui.command.handler.util;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class UploadFile {
public static void main(String[] args) {
// String urlPath="http://127.0.0.1:30002/upService/uploadFile";
String remotePath = "/fdir/fileUpload/";
// String localPath="D:\\Desktop\\pic\\a.jpg";
String urlPath="http://127.0.0.1:30002/upService/uploadMoreFile";
String localPath="D:\\Desktop\\pic\\a.jpg,D:\\Desktop\\pic\\b.jpg";
String result=testMorePost(urlPath,localPath,remotePath);
System.out.println(result);
}
private static String testPost(String urlPath, String localPath, String remotePath) {
final String remote_url = urlPath;// 第三方服务器请求地址
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
File file=new File(localPath);
String orginName=localPath.substring(localPath.lastIndexOf(".")-1);
HttpPost httpPost = new HttpPost(remote_url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
int i=1;
builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, orginName);// 文件流
builder.addTextBody("destDir", remotePath);// 类似浏览器表单提交,对应input的name和value
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
private static String testMorePost(String urlPath, String localPath, String remotePath) {
final String remote_url = urlPath;// 第三方服务器请求地址
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
HttpPost httpPost = new HttpPost(remote_url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
String[] split = localPath.split(",");
int i=1;
for (String string : split) {
File file=new File(string);
String orginName=string.substring(string.lastIndexOf(".")-1);
builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, orginName);// 文件流
}
builder.addTextBody("destDir", remotePath);// 类似浏览器表单提交,对应input的name和value
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
3.2 代码实现2(只能单文件上传)
package cn.com.agree.ab.a5.client.gui.aui.command.handler.util;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
public class FileTransferUtil {
private static Log logger = LogFactory.getLog(FileTransferUtil.class);
public static void main(String[] args) {
String serverApi="http://127.0.0.1:30002/upService/uploadFile";
String remotePath = "/fdir/fileUpload/";
String localFileMd5 = null;
String localPath="D:\\Desktop\\pic\\a.jpg";
File localFile = new File(localPath);
// try {
// httpUploadFile(serverApi, remotePath, localFileMd5, localFile);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
uploadImg(localPath, serverApi);
}
/**
* @author qimh
* @description 模拟form表单,上传图片
* @param fileName -- 图片路径
* @return 接口返回的json数据
* 原理:模拟form表单提交:把请求头部信息和和img 信息 写入到输出流中,
* 通过流把img写入到服务器临时目录里,然后服务器再把img移到指定的位置
* 最后通过写入流来获取post的响应信息。
*
*/
public static void uploadImg(String fileName,String ECSheng) {
try {
// 换行符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定义数据分隔线
String BOUNDARY = System.currentTimeMillis()+"";
// 服务器的域名
URL url = new URL(ECSheng);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置为POST情
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求头参数
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 上传文件
File file = new File(fileName);
StringBuilder sb = new StringBuilder();
sb.append(boundaryPrefix);
sb.append(BOUNDARY);
sb.append(newLine);
// 文件参数,photo参数名可以随意修改
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName
+ "\"" + newLine);
sb.append("Content-Type:image/jpeg");
// 参数头设置完以后需要两个换行,然后才是参数内容
sb.append(newLine);
sb.append(newLine);
// 将参数头的数据写入到输出流中
out.write(sb.toString().getBytes());
// 数据输入流,用于读取文件数据
DataInputStream in = new DataInputStream(new FileInputStream(file));
byte[] bufferOut = new byte[1024];
int bytes = 0;
// 每次读1KB数据,并且将文件数据写入到输出流中
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
// 最后添加换行
out.write(newLine.getBytes());
in.close();
// 定义最后数据分隔线,即--加上BOUNDARY再加上--。
byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
.getBytes();
// 写上结尾标识
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应 ----读取返回的结果
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = reader.readLine()) != null) {
// System.out.println(line);
JSONObject jsonObject = new JSONObject(line);//创建jsonObjec对象
String json = jsonObject.toString();//josn格式的字符串
System.out.println(json);
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
}
}
4.附 Java代码调用服务端接口进行文件下载
package cn.com.agree.ab.a5.client.gui.aui.command.handler.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class DowndFile {
public static void main(String[] args) {
// String urlPath="http://127.0.0.1:30002/upService/uploadFile";
String filePath = "/fdir/fileUpload/fjl.png";
// String localPath="D:\\Desktop\\pic\\a.jpg";
String urlPath="http://127.0.0.1:30002/downService/downloadFile";
String isAbsolutePath="false";
String result=testPost(urlPath,filePath,isAbsolutePath);
System.out.println(result);
}
private static String testPost(String urlPath, String filePath, String isAbsolutePath) {
final String remote_url = urlPath;// 第三方服务器请求地址
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
HttpPost httpPost = new HttpPost(remote_url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
int i=1;
builder.addTextBody("filePath", filePath);// 类似浏览器表单提交,对应input的name和value
builder.addTextBody("isAbsolutePath", isAbsolutePath);// 类似浏览器表单提交,对应input的name和value
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
InputStream content = responseEntity.getContent();
BufferedInputStream bis = new BufferedInputStream(content);
// 写入本地 D 盘
File file = new File("D:/test.jpg");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] byt = new byte[1024 * 8];
Integer len = -1;
while ((len = bis.read(byt)) != -1) {
bos.write(byt, 0, len);
}
bos.close();
bis.close();
// 将响应内容转换为字符串
// result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}