上传文件至服务器,需要用到一个开源工具,file-upload.jar
下载路径是file-upload.jar
在webcontent下建立一个新的文件夹upload
String uploadPath = getServletContext().getRealPath("upload");//上传的文件的保存路径
Servlet文件
package main.web;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**上传文件至服务器
* Servlet implementation class FileUploadServlet
*/
@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String uploadPath = "";
/**
* @see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
public void init(){
uploadPath = getServletContext().getRealPath("upload");
System.out.println(uploadPath);
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("upload file....");
request.setCharacterEncoding("UTF-8");
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
return;
}
//直接用getParameter()返回null
//String filePath = request.getParameter("filepath");
//System.out.println(filePath);
// ①Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("filepath");
factory.setRepository(repository);
// ②Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items =null;
// ③Parse the request,一个fileitem对象对应一个form表单域
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//遍历表单域
for(FileItem item :items){
if(item.isFormField()){//普通表单域
String value = item.getString("UTF-8");
String fieledName = item.getFieldName();//表单的name属性
System.out.println(value+" "+fieledName);
}else{//上传文件域
String value = item.getName();
String fieledName = item.getFieldName();//表单name属性
System.out.println(value+" "+fieledName);
try {
item.write(new File(uploadPath+File.separator+item.getName()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
jsp文件
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="fileupload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/>
<input type="file" name="filepath"/>
<input type="submit" value="上传">
</form>
</body>
</html>