文件上传–构建基本的上传表单

1.控制器加载视图文件

package masterSpringMvc.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UploadController
{
    @RequestMapping("/upload/")
   
    public String upload()
    {
        return "upload";
    }
   
}
2.视图文件实现一个基本的表单

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta content="text/html;charset=UTF-8"/>
    <title>hello</title>
</head>
<body>
    upload page
<br>
<form th:action="@{/upload/}" method="post" enctype="multipart/form-data">
<input type="file" name="upload_file" />
<button type="submit" name="save" th:text="#{submit}"></button>
</form>   
</body>
</html>
3.建立I18N

messages_zh_CN.properties
messages.properties
4.固化语言

applicatoin.properties
 
spring.mvc.locale=zh_CN
spring.mvc.locale-resolver=FIXED
5.处理POST保存图片

package masterSpringMvc.Controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController
{
public static final Resource PICTURES_DIR = new FileSystemResource("./pictures");
    @RequestMapping("upload")
   
    public String upload()
    {
        return "upload";
    }
   
    @RequestMapping(value="/upload",method=RequestMethod.POST)
    public String onUpload(MultipartFile file) throws IOException
    {
    String filename = file.getOriginalFilename();
    File tempFile = File.createTempFile("pic", getFileExtension(filename),PICTURES_DIR.getFile());
   
    try(InputStream in = file.getInputStream();OutputStream out = new FileOutputStream(tempFile))
    {
    IOUtils.copy(in, out);
    }
   
   
    return "upload";
    }
   
    private static String getFileExtension(String name)
    {
    return name.substring(name.lastIndexOf("."));
    }
   
}