<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
客户端
// 创建默认的httpClient实例.
HttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(UploadService);
// 创建参数队列
FileBody bin = new FileBody(new File("D:\\download\\1.jpg"));
// StringBody pathBody = new
// StringBody("/20170317/",ContentType.DEFAULT_TEXT);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody("uploadFile", new File("D:\\download\\1.jpg"))
.addTextBody("path", "/20170317/").build();
try {
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getURI());
HttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out
.println("--------------------------------------");
System.out.println("Response content: "
+ EntityUtils.toString(entity, "UTF-8"));
System.out
.println("--------------------------------------");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
服务端
try {
System.out.println("IP:" + request.getRemoteAddr());
String path= request.getParameter("path");
Part part1= request.getPart("path");
Iterator<Part>iterator=request.getParts().iterator();
while (iterator.hasNext()) {//遍历客户端上传的所有文件
Part part = (Part) iterator.next();
System.out.println(part.getContentType());
}
String username =request.getParameter("username");
System.out.println("username:" + username);
// 1、创建工厂类:DiskFileItemFactory
DiskFileItemFactory facotry = new DiskFileItemFactory();
String tempDir = getServletContext().getRealPath("/WEB-INF/upload");
facotry.setRepository(new File(tempDir));//设置临时文件存放目录
// 2、创建核心解析类:ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(facotry);
upload.setHeaderEncoding("UTF-8");// 解决上传的文件名乱码
upload.setFileSizeMax(1024 * 1024 * 1024);// 单个文件上传最大值是1M
upload.setSizeMax(2048 * 1024 * 1024);//文件上传的总大小限制
// 3、判断用户的表单提交方式是不是multipart/form-data
boolean bb = upload.isMultipartContent(request);
if (!bb) {
response.setCharacterEncoding("utf-8");
response.getWriter().print("不是multipart/form-data");
return;
}
// 4、是:解析request对象的正文内容List<FileItem>
List<FileItem> items = upload.parseRequest(request);
String dirString =path.substring(0,path.lastIndexOf("/"));
String filenameString=path.substring(path.lastIndexOf("/")+1);
String storePath = getServletContext().getRealPath(dirString);// 上传的文件的存放目录
for (FileItem item : items) {
if (item.isFormField()) {
// 5、判断是否是普通表单:打印看看
String fieldName = item.getFieldName();// 请求参数名
String fieldValue = item.getString("UTF-8");// 请求参数值
System.out.println(fieldName + "=" + fieldValue);
} else {
// 6、上传表单:得到输入流,处理上传:保存到服务器的某个目录中,保存时的文件名是啥?
String fileName = item.getName();// 得到上传文件的名称 C:\Documents
// and
// Settings\shc\桌面\a.txt
// a.txt
//解决用户没有选择文件上传的情况
if(fileName==null||fileName.trim().equals("")){
continue;
}
fileName = fileName
.substring(fileName.lastIndexOf("\\") + 1);
String newFileName = fileName;
System.out.println("上传的文件名是:" + filenameString);
InputStream in = item.getInputStream();
String savePath = makeDir(storePath, filenameString);
OutputStream out = new FileOutputStream(savePath);
byte b[] = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
in.close();
out.close();
item.delete();//删除临时文件
response.getWriter().print(fileName);
}
}
}catch(FileUploadBase.FileSizeLimitExceededException e){
response.getWriter().print("单个文件大小不能超出5M");
request.setAttribute("message", "单个文件大小不能超出5M");
request.getRequestDispatcher("/message.jsp").forward(request,
response);
}catch(FileUploadBase.SizeLimitExceededException e){
response.getWriter().print("总文件大小不能超出7M");
}catch (Exception e) {
e.printStackTrace();
response.getWriter().print("上传失败");
}
服务端 String path= request.getParameter("path"); 为null。
Part part1= request.getPart("path"); 这个是有的 但是变成流了
认证0级讲师