SpringMVC basics--upload query files to the server

Configure spring's front-end controller and view parser in advance.

Traditional java file upload

Dependent jar packages

<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>

Submit the form of the file
Change the submission method to post, and change the enctype type to multipart/form-data

<h1>传统方式上传文件</h1>
<form action="user/uploadFile" method="post" enctype="multipart/form-data">
     选择文件:<input type="file" name="upload"><br>
     <input type="submit" value="上传文件">
</form>

The controller handles the request and uploads the file

@RequestMapping("/uploadFile")
    public String testUploadFile(HttpServletRequest request) throws Exception {
    
    
        System.out.println("开始上传文件");
        // 获取要上传文件的目录
        String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
        // 创建File对象,一会向该路径下传送文件
        File file = new File(realPath);
        // 判断路径是否存在,如果不存在创建该目录
        if (!file.exists()) {
    
    
            file.mkdirs();
        }
        // 创建磁盘文件项工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        // 解析request对象
        List<FileItem> list = fileUpload.parseRequest(request);
        // 遍历
        for (FileItem fileItem: list) {
    
    
            // 判断文件项是普通字段还是上传的文件
            if (fileItem.isFormField()) {
    
    

            } else {
    
    
                // 上传文件项
                String filename = fileItem.getName();
                // 上传文件
                fileItem.write(new File(file,filename));
                // 删除临时文件
                fileItem.delete();
            }
        }
        return "success";
    }

Run with tomcat, and finally upload the file to the working directory of the project under the tomcatWebapp file.

Upload files in SpringMVC mode

springmvc can configure file parsers to replace the traditional
process of creating file item factories and traversing and parsing request objects. These springmvc file parsers will do it for us.
The first step is to configure the file parser

<!-- 配置文件解析器,要求id名称必须是multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<!-- 设置文件最大内存 -->
        <property name="maxUploadSize" value="10485760"></property>
    </bean>

Form for submitting documents

    <h1>SpringMVC方式上传文件</h1>
    <form action="user/uploadFile2" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload"><br>
        <input type="submit" value="上传文件">
    </form>

The controller handles the request and submits the file

    @RequestMapping("/uploadFile2")
    public String testUploadFileMvc(HttpServletRequest request, MultipartFile upload) throws Exception {
    
    
        // 获取要上传文件的目录
        String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
        // 创建File对象,一会向该路径下传送文件
        File file = new File(realPath);
        // 判断路径是否存在,如果不存在创建该目录
        if (!file.exists()) {
    
    
            file.mkdirs();
        }
        // 获取上传文件名称
        String  filename = upload.getOriginalFilename();
        // 防止重名文件覆盖,重新生成文件名称唯一化
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        filename = uuid+"_"+filename;
        // 上传文件,上传过后会自动给我们删除文件缓存。
        upload.transferTo(new File(file,filename));
        return "success";
    }

Upload files across servers to the server

What I did before is to upload to the local server. Now build another project and set tomcat to port 8081, which is equivalent to a project running on port 8080, and transfer the file to port 8081. The 8081 server does not need to set anything, just create a Meaven project and choose any webapp.
Introduce maven coordinates

<dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-core</artifactId>
      <version>1.19.4</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-client</artifactId>
      <version>1.19.4</version>
    </dependency>

form

    <h1>SpringMVC方式上传到图片服务器</h1>
    <form action="user/uploadFile3" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload"><br>
        <input type="submit" value="上传文件">
    </form>

The controller processes the request and uploads to the 8081 server

@RequestMapping("/uploadFile3")
    public String testUploadFileService(MultipartFile upload) throws Exception {
    
    
        System.out.println("向服务器上传文件");
        // 定义图片服务器的请求路径
        String path = "http://localhost:8081/uploadService_war_exploded/";

        // 获取上传文件名称
        String  filename = upload.getOriginalFilename();
        // 防止重名文件覆盖,重新生成文件名称唯一化
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        filename = uuid+"_"+filename;
        // 向图片服务器上传文件
        // 创建客户端对象
        Client client = Client.create();
        // 连接图片服务器
        WebResource resource = client.resource(path + filename);
        // 上传文件
        System.out.println("准备上");
        resource.put(upload.getBytes());
        return "success";
    }

If error 405 is reported, you need to set conf/web.xml in the tomcat directory to read-only false, and add the following configuration at the specified location.

	<init-param>
			<param-name>readonly</param-name>
			<param-value>false</param-value>
		</init-param>

This file will be sent to the target directory of the project directory.

Guess you like

Origin blog.csdn.net/qq_44660367/article/details/108943109