jspは簡単なファイルのアップロードとダウンロード機能を実現する

32773 ワード

家でぶらぶらしていると、勉強で退屈を解消するしかなく、ちょうどjspを学んだ(これは時代遅れだと言う人が多いが、学校は勉強しなければならないし、知識面を広げても悪くない...).ブログの中でもしどこが間違っているならば、また大きい人が伝言あるいはメールボックスの方式で指摘することを望んで、メールボックスの住所[email protected]
一.ファイルのアップロード
  • フロントエンドjspファイルコードを貼ってください(極めて粗末ですが...)
  • <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="img">
        <input type="submit" value="  ">
    </form>
    <a href="/download?filename=2.jpg">  </a>
    </body>
    </html>
    
    
  • バックエンドサーブレットコードは、2つのjarパッケージ(1:commons-fileupload-1.3.1.jar 2:commons-io-2.4.jar)
  • を使用します.
    package com.home.lyp.servlet;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadBase;
    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.io.UnsupportedEncodingException;
    import java.util.List;
    
    @WebServlet(name = "UploadServlet",urlPatterns = "/upload")
    public class UploadServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp){
            doPost(req,resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp){
            try {
                req.setCharacterEncoding("utf-8");
                resp.setCharacterEncoding("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
    
            //   
            boolean flag = ServletFileUpload.isMultipartContent(req);
            if (flag){
                DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
                ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
                //             
                fileItemFactory.setSizeThreshold(1024*2);
                String pathTemp = req.getSession().getServletContext().getRealPath("uploadtemp");
                //         
                fileItemFactory.setRepository(new File(pathTemp));
                //         
                servletFileUpload.setSizeMax(1024*1024);
                try {
                    List<FileItem> items = servletFileUpload.parseRequest(req);
                        for (FileItem item : items) {
                            //      name   
                            String name = item.getFieldName();
                            if (name.equals("img")){
                                //item.getString();
                                System.out.println(name);
                                //       
                                String FileName = item.getName();
                                //              
                                String ext = FileName.substring(FileName.indexOf(".")+1);
                                System.out.println(ext);
                                if(!(ext.equals("png") || ext.equals("jpg") || ext.equals("gif") || ext.equals("jpeg"))){
                                    System.out.println("      ");
                                    req.getRequestDispatcher("succes.jsp").forward(req,resp);
                                    return;
                                }else {
                                    //     
                                    String path = req.getSession().getServletContext().getRealPath("upload");
                                    File file = new File(path,FileName);
                                    item.write(file);
                                }
                            }
                        }
                } catch (FileUploadBase.SizeLimitExceededException e){
                    System.out.println("          ");
                }
                catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                req.getRequestDispatcher("succes.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    

    二、ダウンロード
    package com.home.lyp.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URLEncoder;
    
    
    @WebServlet(name = "DownloadServlet", urlPatterns = "/download")
    public class DownloadServlet extends HttpServlet {
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           doGet(req,resp);
    
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            String filename =  req.getParameter("filename");
            //            
           // System.out.println(filename);
            resp.addHeader("content-Type","application/octet-stream");//      
            //   ie            URLEncoder.encode(filename,"utf-8")
            resp.addHeader("content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
    
            // servlet                   servlet 
            InputStream inputStream = getServletContext().getResourceAsStream("/res/"+filename);
            //System.out.println(inputStream);
            //      
            ServletOutputStream outputStream = resp.getOutputStream();
            //   
            byte[] bs = new byte[1024];
            int len ;
          
            while ((len = inputStream.read(bs))!=-1){
                outputStream.write(bs,0,len);
            }
            inputStream.close();
            outputStream.close();
        }
    }