SpringMVC Learning (Four) ------ file upload

First, the file upload process

  1. Build file name
  2. Sets the server file path stored
  3. Dump the specified path

Second, the case

  1. Introducing the desired configuration package and jar
    Here Insert Picture Description
  2. Add SpringMVC the configuration file is a file upload component for
<!--注册文件上传组件-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
  1. Imageupload.jsp a page to create a form for file upload
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/admin/up.action" method="post" enctype="multipart/form-data">
    <p>图片:</p>
    <input type="file" name="upload">
    <input type="submit" value="上传">
</form>
</body>
</html>

  1. Create a New Tools FileNameUtil.java utils package and add the file name processing
package com.oracle.utils;

import java.util.UUID;

public class FileNameUtil {
	//根据UUID生成文件名去掉UUID之间的横杠
	public static String getUUIDFileName() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replace("-", "");
	}
	//从请求头中提取文件名和类型
	public static String getRealFileName(String context) {
		// Content-Disposition: form-data; name="upload"; filename="a_left.jpg"
		int index = context.lastIndexOf("=");
		String filename = context.substring(index + 2, context.length() - 1);
		return filename;
	}
	//根据给定的文件名和后缀截取后缀
	public static String getFileType(String fileName){
		//9527s.jpg
		int index = fileName.lastIndexOf(".");
		return fileName.substring(index);

		//8b7cb153974c4947ad6934a3213dd1f4.jpg
	}
}

  1. Create a package images in the web directory for storing files
  2. Create a display picture show.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
图片:<img src="${pageContext.request.contextPath}/images/${imgname}">
</body>
</html>

  1. Create a new controller components written file upload method
    ImageUploadAction.java
package com.oracle.controller;

import com.oracle.utils.FileNameUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/admin")
public class ImageUploadAction {
    @RequestMapping("/up")
    public  String up(@RequestParam MultipartFile upload, HttpServletRequest request){
        //构建文件名,使用UUID起名,使用原始文件的后缀
         String saveFileName= FileNameUtil.getUUIDFileName()+FileNameUtil.getFileType(upload.getOriginalFilename());
        System.out.println("构建的文件名字"+saveFileName);
         //指定服务器端存储路径
          String path=request.getServletContext().getRealPath("/images");
        System.out.println("服务器端存储路径"+path);
        //进行文件流转存 C:\Users\25717\Desktop\idea-workspace\springmvc_01\web\images\
        //try catch快捷键 ctrl+alt+t
        try {
            upload.transferTo(new File(path+saveFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        request.setAttribute("imgname",saveFileName);
        return "show";
    }
}

  1. Before running the project name suffix changed web or can not be stored in files to images
    Here Insert Picture Description
  2. Run the project, the project will jump to the default index.jsp page, you need to manually imageupload.jsp run, and because registration springmvc suffix is ​​action so you need to manually change jsp
    Here Insert Picture DescriptionHere Insert Picture Description
  3. Operating results.
    Here Insert Picture DescriptionClick Upload
    Here Insert Picture DescriptionHere Insert Picture Description
Published 19 original articles · won praise 6 · views 1039

Guess you like

Origin blog.csdn.net/weixin_43288999/article/details/104691231