1.前端页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传测试</title>
</head>
<body>
<!-- method一定要是POST
enctype="multipart/form-data 发送以 multipart/form-data 编码的表单数据"
-->
<form action="/li/fileUpload" method="POST" enctype="multipart/form-data">
<!-- type要是file类型 -->
<input type="file" name="file"/>
<button >提交</button>
</form>
</body>
</html>
注意点:
1.请求方式必须是POST
2.enctype="multipart/form-data"必须写
实际效果图:
2.Controller层代码
package com.li.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.li.service.FileUploadService;
@Controller
@RequestMapping("/li/")
public class FileUploadController {
@Autowired
private FileUploadService fileUploadService;
@RequestMapping("fileUpload")
@ResponseBody
public String fileUpload(MultipartFile file) {
fileUploadService.uploadFile(file);
return "上传成功";
}
}
3.service层代码
package com.li.service.impl;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.li.service.FileUploadService;
@Service
public class FileUploadServiceImpl implements FileUploadService {
@Override
public void uploadFile(MultipartFile file) {
//1.获取文件原名称
String fileName = file.getOriginalFilename();
//2.获取文件后缀名
String fileSuffixName = fileName.substring(fileName.indexOf("."));
//3.文件上传后保存路径
String dateDir = new SimpleDateFormat("/yyyy-MM-dd/").format(new Date()).toString();
String savePath = "F:/JavaTest/FileUpload"+dateDir;
File filePath = new File(savePath);
//4.判断文件路径是否存在,如果不存在就新创建
if(!filePath.exists()) {
filePath.mkdirs();
}
//5.为了防止文件名相同出现覆盖的情况需要给文件重命名
String newFileName = new SimpleDateFormat("yyyy-MM-dd_HHMMSS").
format(new Date()).toString()+fileSuffixName;
//6.创建文件
File newFile = new File(filePath+"/"+newFileName);
//7.将上传的文件输出到刚创建的文件
try {
file.transferTo(newFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上传后生成的文件:
注意:默认上传文件为1M,超过1M上传会报错