1.upLoadPage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<form action="upload" method="post" enctype="multipart/form-data">
选择图片:<input type="file" name="file" accept="image/*" /> <br>
<input type="submit" value="上传">
</form>
2.UploadController
package com.example.demo_zhang.web;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
@RequestMapping("/uploadPage")
public String uploadPage() {
return "uploadPage";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(HttpServletRequest req, @RequestParam("file") MultipartFile file,Model m) {
try {
//文件名+时间戳,File.separator相当于“/”
String fileName = System.currentTimeMillis()+file.getOriginalFilename();
String destFileName=req.getServletContext().getRealPath("")+"uploaded"+File.separator+fileName;
//创建目录
File destFile = new File(destFileName);
destFile.getParentFile().mkdirs();
//将图片移到指定目录下
file.transferTo(destFile);
m.addAttribute("fileName",fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
}
return "showImg";
}
}
3.application.properties加入以下内容,设置文件大小
spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb
4.showImg.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<img src="/uploaded/${fileName}">
5.运行,http://127.0.0.1:8080/uploadPage,且上传文件后跳转至http://127.0.0.1:8080/upload