这种方式下,其实无需任何配置。只需按正常的web开发项目集成即可
添加普通web项目依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
修改配置文件(可选)
配置上传文件信息
http:
multipart:
# 最大支持文件大小 即单个文件大小
max-file-size: 2m
# 最大支持请求大小 即一次性上传的总文件大小
max-request-size: 10m
使用
package Cc.LiSen.Controllers;
import com.sun.jmx.snmp.agent.SnmpMibAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestController
public class J2EEFileUpload {
private static final Logger logger = LoggerFactory.getLogger(J2EEFileUpload.class);
@PostMapping("/upload")
@ResponseBody
public String UploadFile(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
if (file.isEmpty()) {
return "上传文件不能为空";
}
String fileType = file.getContentType();
String fileName = file.getName();
String originalName = file.getOriginalFilename();
long fileSize = file.getSize();
logger.info("原始文件名为:" + originalName);
logger.info("服务器文件名为:" + fileName);
logger.info("文件大小为:" + String.valueOf(fileSize));
String fileSavePath = request.getServletContext().getRealPath("/static/upload/");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddd");
fileSavePath = fileSavePath + simpleDateFormat.format(new Date())+"//";
fileSavePath = fileSavePath.replace("//",File.separator);
File saveFile = new File(fileSavePath+originalName);
if(!saveFile.getParentFile().exists()){
saveFile.getParentFile().mkdirs();
}
file.transferTo(saveFile);
return "上传成功";
}
}
感谢分享
好东西