• servlet3.0 文件上传功能


    注意 jsp页面中file选择 的要有属性 name='file'
    package com.webserver.webservice;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    import org.apache.catalina.core.ApplicationPart;
    
    /**
     * Servlet implementation class UpLoadServlet
     * author:chuanyuBai 2014/07/21
     */
    @MultipartConfig(location = "D:/upload", fileSizeThreshold = 1024)
    public class PCMUploadServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public PCMUploadServlet() {
            super();
        }
    
        @Override
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        }
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
            request.setCharacterEncoding("utf-8");
            try{
                //获取多文件
                List<Part> partlist =  (List<Part>) request.getParts();
                //获取单文件文件部件part
                Part part = request.getPart("file");
                //获取文件名称的两种方式
                //方式一
                String filename1 = ((ApplicationPart)part).getFilename();
                //方式二
                //获取文件服务器头部信息
                String h = part.getHeader("content-disposition");
                String filename = h.substring(h.lastIndexOf("=") + 2, h.length() - 1);
                String root = request.getServletContext().getRealPath("/upload");
                File f=new File(root);  
                f.mkdir();  
                //删除生成的中间文件
                part.delete();
                part.write(root+"/"+filename);
            }catch(Exception e){
                System.out.println(e.getMessage());
            }
        
        }
        
    
    }
  • 相关阅读:
    console一闪而过的解决办法
    关于return
    各种js验证(笔记本)
    订单号的生成
    linux之cp/scp命令+scp命令
    11111111111
    Servlet中Web.xml文件的配置
    maven pom.xml详解
    环形缓冲区类(C++)附测试程序(转)
    环形缓冲区类(C++)绝对可用(转)
  • 原文地址:https://www.cnblogs.com/Wen-yu-jing/p/3858425.html
Copyright © 2020-2023  润新知