编程知识 cdmana.com

What are the ways to upload files in Java Web?

Last time we talked about how to download files , This time, we will simply talk about the ways to upload files from different environments .

How to upload files

  • Servlet2.5 The way
  • Servlet3.0 The way
  • SpringMVC The way

Case practice

Servlet2.5 The way

File upload involves the preparation of front page and background server-side code , The front desk sends files , Receiving and saving files in the background , This is a complete file upload .

1) Foreground page

When uploading files , There will be an interface for uploading files , First we need a form , And the form request way is POST; Second, ours form Form enctype Must be set to ”multipart/form-data” namely enctype="multipart/form-data" It means to set up the form MIME code . By default, the encoding format is ”application/x-www-form-urlencoded”, Cannot be used for file upload ; Only used multipart/form-data In order to transfer file data completely .

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Upload files </title>
</head>
<body>
    <form action="uploadServlet" method="post" enctype="multipart/form-data">
         file :<input type="file" name="myfile"/>
        <input type="submit" value=" Upload " />
    </form>
</body>
</html>

2) backstage commons-fileupload Use

First, you need to import a third party jar package ,<http://commons.apache.org/>; download commons-io and commons-fileupload Two jar Resources for . Unzip and import into the project .commons-fileupload.jar It's the core package of file upload commons-io.jar yes fileupload The dependency package of , It's another toolkit at the same time .

JavaWeb What are the ways to upload files in ?

Introduce several core classes used

  DiskFileItemFactory – Set up disk space , Save temporary files . Just a tool class

  ServletFileUpload – File upload core class , Such reception request, And analyze

  ServletFileUpload.parseRequest(request); – List analysis request

  1、 Create a DiskFileItemFactory Factory , And make temporary files and sizes

  2、 establish ServletFileUpload Core class , Receiving temporary files , Do the requested conversion

  3、 adopt ServletFileUpload Class conversion original request , obtain FileItem aggregate

  4、 Traverse the elements in the collection and process

  5、 Determine whether each element is a normal form item , If so, it will be treated as a normal form item

  6、 If it's not a normal form item , File , To deal with by means of processing ( Upload )

public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //  Set the code , You can get the Chinese file name 
        request.setCharacterEncoding("UTF-8");
        //  obtain tomcat Under the upload Path to directory 
        String path = getServletContext().getRealPath("/upload");
        //  Temporary file directory 
        String tempPath = getServletContext().getRealPath("/temp");
        //  Check if we have a file upload request 
        // boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        // 1、 Statement DiskFileItemFactory Factory , Used to set a temporary directory on the specified disk 
        DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, new File(tempPath));
        // 2、 Statement ServletFileUpload, Receive the temporary file above . You can also default to 
        ServletFileUpload up = new ServletFileUpload(disk);
        // 3、 analysis request
        try {
            List<FileItem> list = up.parseRequest(request);
            if (list.size() > 0) {
                for (FileItem file : list) {
                    //  Determine whether it is a normal form item 
                    if (file.isFormField()) {
                        String fieldName = file.getFieldName();
                        //  Chinese garbled , At this time, you need to specify the encoding method for obtaining data 
                        // String value = file.getString();
                        String value = file.getString("UTF-8");
                        System.out.println(fieldName + "=" + value);
                    } else { //  The description is a document 
                        //  Get the name of the file itself 
                        String fileName = file.getName();
                        System.out.println(file.getFieldName());
                        //  Processing file name 
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                        System.out.println("old Name : " + fileName);
                        //  Modify name 
                        String extName = fileName.substring(fileName.lastIndexOf("."));
                        String newName = UUID.randomUUID().toString().replace("-", "") + extName;
                        //  Save the new name , And write it in a new file 
                        file.write(new File(path + "/" + newName));
                        System.out.println(" The file name is :" + fileName);
                        System.out.println(" File size is :" + file.getSize());
                        file.delete();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Servlet3.0 The way

Using annotations @MultipartConfig Will a Servlet Mark to support file upload .Servlet3.0 take multipart/form-data Of POST The request is encapsulated as Part, adopt Part Operate on the uploaded file .

The front desk

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Upload files </title>
</head>
<body>
    <form action="upload" method="post" enctype="multipart/form-data">
         full name :<input type="text" name="uname"/>
         file :<input type="file" name="myfile"/>
        <input type="submit" value=" Upload " />
    </form>
</body>
</html>

backstage

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(" Upload files ...");
        //  Set encoding 
        request.setCharacterEncoding("UTF-8");
        //  Get normal form item parameters 
        String uname = request.getParameter("uname");
        System.out.println(uname);
        //  Upload files 
        //  obtain part object  request.getpart(name):name It stands for in the form file Elemental name Property value 
        Part part = request.getPart("myfile");
        //  Get the file storage path 
        String path = request.getServletContext().getRealPath("/");
        //  Get the filename 
        String fileName = part.getSubmittedFileName();
        //  Upload 
        part.write(path + fileName);
    }

}

SpringMVC The way

Pom File modification add to commons-fileupload rely on

<dependency> 

    <groupId>commons-fileupload</groupId> 

    <artifactId>commons-fileupload</artifactId> 

    <version>1.3.2</version> 

</dependency> 

servlet-context.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <property name="maxUploadSize"> 

    <value>104857600</value> 

    </property> 

    <property name="maxInMemorySize"> 

    <value>4096</value> 

    </property> 

</bean> 

FileController

import java.io.File; 

import java.io.IOException; 

import javax.servlet.http.HttpServletRequest; 

import org.springframework.stereotype.Controller; 

import org.springframework.web.bind.annotation.RequestMapping; 

import org.springframework.web.multipart.MultipartFile; 

import org.springframework.web.multipart.MultipartHttpServletRequest; 

import org.springframework.web.servlet.ModelAndView; 

@Controller 

public class FileController { 

    @RequestMapping("/uploadFile") 

    public ModelAndView uploadFile(HttpServletRequest request){ 

        ModelAndView mv=new ModelAndView(); 

        mv.setViewName("result"); 

        MultipartHttpServletRequest mr=(MultipartHttpServletRequest) request; 

        MultipartFile multipartFile= mr.getFile("file"); 

        String path=request.getSession().getServletContext().getRealPath("upload"); 

        System.out.println(path); 

        if(null!=multipartFile&&!multipartFile.isEmpty()){ 

            String fileName=multipartFile.getOriginalFilename(); 

        try { 

            multipartFile.transferTo(new File(path,fileName)); 

            mv.addObject("msg", " File upload succeeded !"); 

        } catch (Exception e) { 

            mv.addObject("msg", " Upload failed !"); 

            e.printStackTrace(); 

        } 

        } 

        return mv; 

    } 

} 

Front desk forms

<form action="uploadFile" method="post" enctype="multipart/form-data"> 

    <input type="file" name="file"/> 

    <button type="submit">  Submit </button> 

</form> 

Expand ~MIME

MIME(Multipurpose Internet Mail Extensions) Multipurpose Internet mail extension type . A file with an extension is a type of file opened by an application , When the extension file is accessed , The browser opens automatically using the specified application . Mostly used to specify some client-side customized file names , And some ways to open media files .

It's an Internet standard , Extended e-mail standards , To enable it to support :

Not ASCII Character text ; Non text attachments ( Binary system 、 voice 、 Image, etc ); By many parts (multiple parts) The body of the message ; Include non ASCII Character header information (Header information).

This standard is defined in RFC 2045、RFC 2046、RFC 2047、RFC 2048、RFC 2049 etc. RFC in . MIME Improved by RFC 822 Transformed from RFC 2822, These old standards stipulate that e-mail standards are not allowed to be used in e-mail messages 7 position ASCII Characters other than character set . Because of this , Some non English character messages and binaries , Images , Voice and other non text messages could not be transmitted in e-mail (MIME Sure ).MIME Specifies the symbolization method used to represent a variety of data types . Besides , Used in the world wide web HTTP The protocol also uses MIME Framework , The standard has been extended to the Internet media type .

Look at the corresponding file of MIME type , I recommend you a way , With Tomcat For example , Under it web.xml The file can view all the MIME type , adopt Ctrl + F Search quickly to find the file you want to know MIME type .

JavaWeb What are the ways to upload files in ?

版权声明
本文为[osc_ 9f7pxl0m]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224141328317j.html

Scroll to Top