大概
目录结构
这里这几个jar包自己导入就行,第三个是一个大神写的框架,直接搜就能搜到
Android代码:
HttpUtil.java
1 | public class HttpUtil { |
MainActivity.java
1 | public class MainActivity extends AppCompatActivity { |
布局文件(很简单,就两个按钮)
1 | <?xml version="1.0" encoding="utf-8"?> |
配置文件(不要忘了添加一下权限)
1 | <uses-permission android:name="android.permission.INTERNET"></uses-permission> |
本地服务器端
######TestServlet.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@WebServlet(name = "TestServlet",urlPatterns = "/testServlet")
public class TestServlet extends HttpServlet {
private ServletFileUpload mServletFileUpload;
private void initUp() {
if (null == mServletFileUpload) {
File file = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
mServletFileUpload = new ServletFileUpload(new DiskFileItemFactory(
DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, file
));
mServletFileUpload.setFileSizeMax(1024L * 1024 * 100);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println("开始处理请求。。。");
initUp();
response.setHeader("Content-Type", "text/html;charset=utf-8");//指定编码
Map<String, List<FileItem>> fileItemListMap = mServletFileUpload.parseParameterMap(request);
for (Map.Entry<String, List<FileItem>> entry : fileItemListMap.entrySet()) {
List<FileItem> fileItemList = entry.getValue();
if (!fileItemList.isEmpty()) {
for (FileItem fileItem : fileItemList) {
if (!fileItem.isFormField()) {//取非表单属性 ,也就是文件
String fileName = FilenameUtils.getName(new String(fileItem.getName().getBytes(), "utf-8"));
InputStream inputStream = fileItem.getInputStream();
File file = new File("D:/uploads", fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] bytes = new byte[1024 * 8];
int len;
while ((len = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
fileOutputStream.flush();
}
fileOutputStream.close();
PrintWriter writer = response.getWriter();
writer.print(fileName + " ----> ok!!!!!");//成功 ,返回个响应
writer.flush();
}
}
}
}
System.out.println("请求处理结束。");
} catch (FileUploadException e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
效果
把手机模拟器里的 java路线.jpg 文件发送到服务器,经处理后保存到本地 D:\uploads 目录下