本地文件上传到服务器

表单:

 

<form action="A" method="post" enctype="multipart/form-data"> <!-- 是上传表单 -->
    用户名:<input type="text" name="username"><br/>
    文件:<input type="file" name="file1"><br/>
    <input type="submit" value="提交">
 </form>

 

Servlet:

 

public class Servlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建文件上传工厂类
        DiskFileItemFactory fac = new DiskFileItemFactory();
        //2.创建文件上传核心类
        ServletFileUpload upload = new ServletFileUpload(fac);
        //[设置单个文件最大上传大小:30M]
        upload.setFileSizeMax(30*1024*1024);
        //[设置总的文件最大上传大小:50M]
        upload.setSizeMax(50*1024*1024);

        //判断表单是否为文件上传表单
        if(upload.isMultipartContent(request)){
            //3.把请求数据转换为FileItem对象集合
            try {
                List<FileItem> items = upload.parseRequest(request);
                //遍历每一个上传项
                for(FileItem item:items){
                    //再判断是普通表单还是文件上传表单
                    if(item.isFormField()){
                        //普通表单
                        System.out.println("普通表单");
                        //获取元素名称
                        String fileName = item.getFieldName();
                        //获取文本框的值
                        String value = item.getString("UTF-8");
                        System.out.println(fileName+":"+value);

                    }else{
                        //处理文件上传

                        //获取上传文件的名字
                        String name = item.getName();
                        System.out.println(name);
                        //获取上传的目录路径,指定文件存储路径
                        String basePath = "G:/IntelliJ IDEA 2018.2.4/DynamicWeb/src/";  /*绝对路径,存放到服务器中的路径*/
                        //创建文件对象
                        File file = new File(basePath,name);
                        try {
                            item.write(file);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }//写文件
                        item.delete();//删除临时文件
                    }
                }
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
        System.out.println("文件上传异常,不处理!");
    }

    }

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

 

将表单提交到Servlet后,即可实现本地文件上传至指定的服务器目录。

相关文章
相关标签/搜索