web後端 文件上傳

須要Commons-fileupload和commons-io兩個jar包.可搜索apache commons下載java

jar複製在項目下的web->WEB-INF->lib下    複製在apache-tomcat本地文件的lib下web

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

servlet中:tomcat

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);    }}
相關文章
相關標籤/搜索