关于multipart/form-data,可参考https://blog.youkuaiyun.com/zshake/article/details/77985757
客户端
参数解释,上传主方法
private void submit() {
Map<String, Object> params = new HashMap<String, Object>();
//普通表单,key-value
params.put("key", "value");
//图片表单,支持多文件上传,修改参数即可
FormFile[] files = new FormFile[2];
files[0] = new FormFile(String filname, byte[] data, String formname, String contentType);
files[1] = new FormFile(String filname, byte[] data, String formname, String contentType);
//上传方法,回调方法可更新界面
httpService.postHttpImageRequest(url, params, files, new HttpCallBackListener() {
public void onFinish(String response) {
}
public void onError(Exception e) {
}
});
}
图片数据bean
public class FormFile {
/* 上传文件的数据 */
private byte[] data;
/* 文件名称 */
private String filname;
/* 表单字段名称*/
private String formname;
/* 内容类型 */
private String contentType = "application/octet-stream"; //需要查阅相关的资料
public FormFile(String filname, byte[] data, String formname, String contentType) {
this.data = data;
this.filname = filname;
this.formname = formname;
if(contentType!=null) this.contentType = contentType;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getFilname() {
return filname;
}
public void setFilname(String filname) {
this.filname = filname;
}
public String getFormname() {
return formname;
}
public void setFormname(String formname) {
this.formname = formname;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
HttpService
public class HttpService {
public HttpService() {
}
public void postHttpImageRequest(final String netWorkAddress,final Map<String, Object> params,final FormFile[] files,
final HttpCallBackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
String BOUNDARY = "---------7d4a6d158c9"; //数据分隔线
String MULTIPART_FORM_DATA = "multipart/form-data";
URL url = new URL(UrlInterface.UTILS + netWorkAddress);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//允许输入
connection.setDoOutput(true);//允许输出
connection.setUseCaches(false);//不使用Cache
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
//上传的表单参数部分
for (Entry<String, Object> entry : params.entrySet()) {//构建表单字段内容
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
sb.append(entry.getValue());
sb.append("\r\n");
}
DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
outStream.write(sb.toString().getBytes());//发送表单字段数据
//上传的文件部分
for(FormFile file : files){
StringBuilder split = new StringBuilder();
split.append("--");
split.append(BOUNDARY);
split.append("\r\n");
split.append("Content-Disposition: form-data; name=\""+ file.getFormname()+"\"; filename=\""+ file.getFilname() + "\"\r\n");
split.append("Content-Type: "+ file.getContentType()+"\r\n\r\n");
outStream.write(split.toString().getBytes());
outStream.write(file.getData(), 0, file.getData().length);
outStream.write("\r\n".getBytes());
}
byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//数据结束标志
outStream.write(end_data);
outStream.flush();
int cah = connection.getResponseCode();
if (cah != 200) throw new RuntimeException("请求url失败");
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
if (listener != null) {
listener.onFinish(response.toString());
}
outStream.close();
} catch (Exception e) {
if (listener != null) {
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
public interface HttpCallBackListener {
void onFinish(String response);
void onError(Exception e);
}
}
服务端
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
/**
* @see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
// 配置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 设置临时存储目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大文件上传值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 设置最大请求值 (包含文件和表单数据)
upload.setSizeMax(MAX_REQUEST_SIZE);
upload.setHeaderEncoding("UTF-8");
// 构造临时路径来存储上传的文件
// 这个路径相对当前应用的目录
String uploadPath = "/usr/image";
// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
JSONObject jsonRes = null;
String resStr = null;
try {
JSONObject json = new JSONObject();
// 解析请求的内容提取文件数据
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (item.isFormField()) {
json.put(item.getFieldName(), item.getString("UTF-8"));
}else{
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 保存文件到硬盘
item.write(storeFile);
json.put(item.getFieldName(),fileName);
}
}
}
//业务处理
//
//
jsonRes = new JSONObject(resStr);
} catch (Exception ex) {
}
PrintWriter out =response.getWriter();
out.println(jsonRes.toString());
out.close();
}
}