1. ホーム
  2. Web プログラミング
  3. JSP プログラミング

jsp+servletによるファイルアップロード機能の簡易実装(saveディレクトリの改良)

2022-01-18 20:31:07

1. jspフロントエンド

<%--
 Created by IntelliJ IDEA.
 User: Lenovo
 Date: 2020/6/19
 Time: 22:53
 Learn from https://www.bilibili.com/video/BV18z411i7gh?t=23&p=192
 To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>File upload</title>
</head>
<body>
  <! --file-upload requirements for forms -->
  <! --
    1、The request submission method in the form must be POST
    2. The form should specify the submitted request as a multipart request, by adding the enctype attribute to the <form/> tag
      Its value is multipart/form-data
    3、 Form
  -->
  <form method="POST" action="http://localhost:8888/hello/UploadImageServlet" enctype="multipart/form-data& quot;>
    number<input type="text" name="BNO"></br>
    name<input type="text" name="BNAME"></br>
    Photo<input type="file" name="picutreUrl"></br>
    <input type="submit" value="Register">
  </form>
</body>
</html>

2. サーブレットバックエンド

package Servlet.bookServlet;

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.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util;
List; import java.util;


@WebServlet(name = "UploadImageServlet")
public class UploadImageServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request,response);
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1. determine if the request is a multipart request
    if(!ServletFileUpload.isMultipartContent(request)){
      throw new RuntimeException("Current request does not support file upload");
    }
    System.out.println("Start uploading files");
    //2. Create the FileItem factory ==> file written to the hard drive
    try {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      //3. Create temp temporary folder
      String tempPath = "D:\\\tomcat\\\\apache-tomcat-9.0.35-windows-x64\\\\apache-tomcat-9.0.35\\\webapps\\\\\librarySystem\\\\web\\\net\\\\temp& quot;;
      File tempFile = new File(tempPath);
      factory.setRepository(tempFile);
      //4. Set the boundary value for using temporary file, if it is larger than this value, the uploaded file will be saved in the temporary file first, if it is smaller than this value, it will be written to memory directly
      //The unit is bytes
      factory.setSizeThreshold(1024*1024*1);

      // 5. Create the core component for file upload
      // Call ServletFileUpload.parseRequest method to parse the request object and get a List object that holds all the uploaded content.
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setHeaderEncoding("utf-8");//can solve the file name Chinese garbled code
      upload.setFileSizeMax(1024*1024*2);

      String bNo="defaultBNo",bName="defaultBName";
      //6. Parse the request
      List<FileItem> items =upload.parseRequest(request);
      //7. Iterate through the request
      for(FileItem item:items){
        //common form item, upload name, number and other common information for upload i
        if(item.isFormField()){
          String fileName = item.getFieldName();// name property value
          String fileValue = item.getString("utf-8");// name corresponding to the value
          System.out.println(fileName + " -- " + fileValue);
          if(fileName.equalsIgnoreCase("BNO")){
            bNo = fileValue;
          }
          if(fileName.equalsIgnoreCase("BNAME")){
            bName = fileValue;
          }
         }
        else{//Upload images, etc.
          String fileName = item.getName();
          System.out.println("Upload file name:"+fileName);
          String suffix = fileName.substring(fileName.lastIndexOf('.')) ;//Get the file type
          String newFileName = bNo+"_"+bName+suffix;
          System.out.println(newFileName);
          //Get the input stream with the content of the uploaded file
          InputStream is = item.getInputStream();
          //String path = this.getServletContext().getRealPath("/net/bookImage");//get the current item save server address, which is under the web folder
          String path = "D:\\\tomcat\\\apache-tomcat-9.0.35-windows-x64\\\apache-tomcat-9.0.35\\\webapps\\\\librarySystem\\\\web\\\\net\\\bookImage& quot;;
          //there is an upper limit to the number of files in a folder, but you can create subdirectories
            //Get the current system time
            Calendar now = Calendar.getInstance();
            int year = now.get(Calendar.YEAR);
            int month = now.get(Calendar.MONTH) + 1;
            int day = now.get(Calendar.DAY_OF_MONTH);
            path = path+"/"+year+"/"+month+"/"+day;
            //If the directory does not exist, create a new directory directly
            File dirFile = new File(path);
            if(!dirFile.exists()){
              dirFile.mkdirs();
            }
          // Create a target file to save the uploaded file
          File desFile = new File(path,newFileName);
          //create the file output stream
          OutputStream os = new FileOutputStream(desFile);
          //write the input stream data to the output stream
          int len=-1;
          byte[]buf = new byte[1024];
          while((len=is.read(buf))! =-1){
            os.write(buf,0,len);
          }
          //desFile.delete();//delete the temporary file
          os.close();//output stream
          is.close();//input stream
          //delete the temporary file
          item.delete();
        }
      }
    } catch (FileUploadException e) {
      e.printStackTrace();
    }
  }
}

概要

アップロードファイルのjsp+サーブレット簡易実装(保存ディレクトリの改善)についてのこの記事は、このに導入され、アップロードファイルの内容のより関連するjspサーブレット実装は、スクリプト家の以前の記事を検索してくださいまたは次の関連記事を閲覧し続けるあなたは将来的に多くのスクリプト家をサポートして願っています!.