• JavaWeb——文件上传


    HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="/WEB16/upload" method="post" enctype="multipart/form-data">
            <input type="text" name="text">
            <input type="file" name="filename">
            <input type="submit">
        </form>
    </body>
    </html>
    

    文件上传(普通版)

    package cn.x5456.uploadDemo;
    
    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.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.List;
    
    @WebServlet(name = "FileuploadServlet")
    public class FileuploadServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            //1.创建磁盘文件项工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2.实例化文件上传核心类
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置上传文件的名称的编码
            upload.setHeaderEncoding("UTF-8");
            //3.解析request---获得文件项集合
            List<FileItem> list = null;
            try {
                 list = upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            //4.遍历集合
            for(FileItem item : list){
                // 判断是否为表单项
                boolean formField = item.isFormField();
                // 表单项
                if(formField){
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    System.out.println(fieldName+":"+fieldValue);
                }// 文件上传项
                else{
                    // 获取文件名
                    String fileName = item.getName();
                    // 获取文件输入流
                    InputStream in = item.getInputStream();
                    // 获取真路径
                    String path = super.getServletContext().getRealPath("WEB-INF/upload");
                    // 设置输出路径
                    OutputStream out = new FileOutputStream(path+"/"+fileName);
                    int len = 0;
                    byte[] b = new byte[1024];
                    while ((len=in.read(b))!=-1){
                        out.write(b,0,len);
                    }
                    in.close();
                    out.close();
                }
            }
    
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    }

    文件上传(缓冲区版)

    package com.itheima;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.List;
    
    import javax.servlet.ServletException;
    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;
    import org.apache.commons.io.IOUtils;
    
    public class FileuploadServlet2 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    		try {
    
    			//1、创建磁盘文件项工厂
    			//作用:设置缓存文件的大小  设置临时文件存储的位置
    			String path_temp = this.getServletContext().getRealPath("temp");
    			//DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024, new File(path_temp));
    			DiskFileItemFactory factory = new DiskFileItemFactory();
    			factory.setSizeThreshold(1024*1024);
    			factory.setRepository(new File(path_temp));
    			//2、创建文件上传的核心类
    			ServletFileUpload upload = new ServletFileUpload(factory);
    			//设置上传文件的名称的编码
    			upload.setHeaderEncoding("UTF-8");
    
    			//ServletFileUpload的API
    			boolean multipartContent = upload.isMultipartContent(request);//判断表单是否是文件上传的表单
    			if(multipartContent){
    				//是文件上传的表单
    				//***解析request获得文件项集合
    				List<FileItem> parseRequest = upload.parseRequest(request);
    				if(parseRequest!=null){
    					for(FileItem item : parseRequest){
    						//判断是不是一个普通表单项
    						boolean formField = item.isFormField();
    						if(formField){
    							//username=zhangsan
    							String fieldName = item.getFieldName();
    							String fieldValue = item.getString("UTF-8");//对普通表单项的内容进行编码
    							
    							System.out.println(fieldName+"----"+fieldValue);
    							
    							//当表单是enctype="multipart/form-data"时 request.getParameter相关的方法
    							//String parameter = request.getParameter("username");
    							
    						}else{
    							//文件上传项
    							//文件的名
    							String fileName = item.getName();
    							//获得上传文件的内容
    							InputStream in = item.getInputStream();
    							String path_store = this.getServletContext().getRealPath("upload");
    							OutputStream out = new FileOutputStream(path_store+"/"+fileName);
    							IOUtils.copy(in, out);
    							in.close();
    							out.close();
    							
    							//删除临时文件
    							item.delete();
    							
    						}
    					}
    				}
    
    			}else{
    				//不是文件上传表单
    				//使用原始的表单数据的获得方式 request.getParameter();
    			}
    		} catch (FileUploadException e) {
    			e.printStackTrace();
    		}
    
    
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    

      

  • 相关阅读:
    戴尔服务器IDRAC命令配置IP地址
    python 生成excel,并下载到本地
    python api
    python发送邮件
    大型线上系统迁移为分布式系统案例
    2014程序员之路
    Java EnumSet工作原理初窥
    C# 引用访问权限
    分享一些我的入门经历
    分享一些我的阅读习惯
  • 原文地址:https://www.cnblogs.com/x54256/p/8456625.html
Copyright © 2020-2023  润新知