1、web端的文件上传。
这里是利用了第三方的jar包。这里所需要的jar包我已经上传到本博客的资源里了,以下是连接
javascript:void(0)
代码如下:
1)login.jsp
<%@ page contentType="text/html; charset=utf-8"%>
<html>
<body>
<form action="http://192.168.1.101:8080/Web3/LoginServlet" method="post" enctype="multipart/form-data">
file:<input name="file" type="file"/><br>
<input type="submit"/>
</form>
</body>
</html>
2)LoginServlet
package com.njupt.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class LoginServlet extends HttpServlet {
public LoginServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
try {
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
String path = request.getSession().getServletContext()
.getRealPath("/files1");
System.out.println(path);
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
for (FileItem item : items) {
if (item.isFormField()) {
} else {
String filename = item.getName();
File file = new File(dir, getFileName(filename));
item.write(file);
}
}
} else {
doGet(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getFileName(String filename) {
if (filename.contains("\\")) {
return filename.substring(filename.lastIndexOf("\\") + 1);
}
return filename;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void init() throws ServletException {
// Put your code here
}
}
2、android文件上传功能的实现
这里也用到了第三方的jar包
下载链接:javascript:void(0)
public boolean uploadFile(String path , String username , String password , String filename) throws Exception{
System.out.println("。。。。。自己写的android短的上传文件.......");
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
PostMethod postMethod = new PostMethod(path);
Part[] parts = new Part[]{
new StringPart("username",username),
new StringPart("password",password),
new FilePart("file",new File(filename))
};
MultipartRequestEntity entity = new MultipartRequestEntity(parts, postMethod.getParams());
postMethod.setRequestEntity(entity);
int responseCode = httpClient.executeMethod(postMethod);
if(responseCode == 200){
return true;
}
return false;
}