web后端 文件上传

时间:2022-07-07 15:08:03

需要Commons-fileupload和commons-io两个jar包.可搜索apache commons下载

jar复制在项目下的web->WEB-INF->lib下    复制在apache-tomcat本地文件的lib下

jsp中 :注意 form的 method="post" enctype="multipart/form-data"   注意input 的name要加上  要加上,不然找不到

servlet中:

package action;

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; 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 java.io.File;
import java.io.IOException;
import java.util.List; /**
* Created by Au on 2015/11/25.
*/
@WebServlet(name = "action")
public class action extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
upLoadFile(request,response);
} catch (Exception e) {
e.printStackTrace();
}
} private void upLoadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();
// 构建文件上传类
ServletFileUpload servletFileUpload=new ServletFileUpload(diskFileItemFactory);
List<FileItem> list=servletFileUpload.parseRequest(request);
for(FileItem fileItem:list) {
// 判断是文字还是文件
if(fileItem.isFormField()){ }else {
String image = fileItem.getName();
String upload_path = request.getSession().getServletContext().getRealPath("/upload3");
// 创建那个文件夹
if(!new File(upload_path).exists()){
new File(upload_path).mkdirs();
}
File real_path = new File(upload_path + "/" + image);
fileItem.write(real_path);
}
}
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}