<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="keywords" content="keyword1,keyword2,keyword3"/>
<meta name="description" content="this is my page"/>
<meta name="content-type" content="text/html; charset=UTF-8"/>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload" th:action="@{/upload}">
图片<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
package com.sicnu.zhijiao.controller;
import com.sicnu.zhijiao.entity.Msg;
import com.sicnu.zhijiao.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
@Controller
public class FileController {
//跳转到上传文件的页面
@RequestMapping(value = "/gouploadimg", method = RequestMethod.GET)
public String goUploadImg() {
//跳转到 templates 目录下的 uploadimg.html
return "uploadimg";
}
//处理文件上传
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String uploadImg(@RequestParam("file") MultipartFile file,
HttpServletRequest request) {
String contentType = file.getContentType();
String fileName = file.getOriginalFilename(); //获取上传文件原名
System.out.println("fileName-->" + fileName);
System.out.println("getContentType-->" + contentType);
String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
try {
FileUtil.uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
System.out.println("文件上传失败");
}
//返回json
return "上传成功";
}
}
package com.sicnu.zhijiao.util;
import java.io.File;
import java.io.FileOutputStream;
public class FileUtil {
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
PrintUtil.println("filePath="+filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
}