jsp中的文件上传

一、jsp端代码

<html>
<head>
    <title>文件上传</title>
</head>
<body>
<form action="./upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">提交</button>
</form>

</body>
</html>

二、servlet端代码

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 org.apache.commons.io.IOUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;


public class upServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setContentType("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //创建文件上传操作工厂(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory)
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //设置缓冲区大小为10kb
        diskFileItemFactory.setSizeThreshold(10240);
        //创建上传组件
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        //设置单个文件上传大小限制
        servletFileUpload.setFileSizeMax(50*10240);
        //解析请求数据(org.apache.commons.fileupload.FileItem)使用到了这个包


        try {
            List<FileItem> list = servletFileUpload.parseRequest(request);
            System.out.print(list);
            for(FileItem item : list){
                //对item进行判断
                if(item.isFormField()){ //如果是普通文本表单字段,返回一个true否则返回一个false。因此可以用该方法判断是否是普通表单域还是文件上传表单域。
                    //不做处理
                }else{
                    //获取输出流 
                 
                    OutputStream os = new FileOutputStream(new File("D:\\"+item.getName()));
                    //将文件保存下来
                    IOUtils.copy(item.getInputStream(),os);

                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        //对list集合进行遍历






    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

三、xml代码

    <servlet>
        <servlet-name>upServlet</servlet-name>
        <servlet-class>upServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>upServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>

 

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页