1、视图层
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传</title>
</head>
<body>
<form action="/uploaded" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
2、上传方法
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
/**
* 文件: UpController
* 描述:
* 创建时间: 2021-12-02 12:59
*
* @author MSCIWANG
*/
@Controller
public class UpController {
@RequestMapping("/upload")
public String upload(){
return "upload";
}
@ResponseBody
@RequestMapping(value = "/uploaded",method = RequestMethod.POST)
public String uploaded(@RequestParam("file") MultipartFile file, HttpServletRequest request){
//String filename=file.getOriginalFilename();
// 创建文件名称
String fileName = UUID.randomUUID() + "."
+ file.getContentType().substring(file.getContentType().lastIndexOf("/") + 1);
//即将要上传的目录
String filepath="h:\\shiro\\upload\\";
try {
uploadfile(file.getBytes(),filepath,filename);
} catch (Exception e) {
e.getMessage();
}
return "上传成功";
}
public void uploadfile(byte[] file,String filepath,String filename) throws IOException
{
File tfile=new File(filepath);
if(!tfile.exists()){
tfile.mkdir();
}
FileOutputStream out = new FileOutputStream(filepath+filename);
out.write(file);
out.flush();
out.close();
}
}