用到的依赖(这些不是必须的,只是为了方便调试使用)
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
package com.xx.demo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@Slf4j
@Api(value = "测试文件上传")
public class Test {
final String path = "G:\\images\\";
@PostMapping("/oneFileUpload")
@ApiOperation(value = "测试单文件上传接口")
public String oneFileUpload (MultipartFile file, String username, String password) throws IOException {
log.info(username + "," + password);
// 判断文件是否为空
if(file == null){
log.info("文件不能为空");
return "文件不能为空";
}else{
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
// 获取文件类型,校验文件的合法性
String contentType = file.getContentType();
if(contentType.contains("image")){
log.info("上传的文件是图片");
// 设置文件存储路径,使用新的文件名,避免文件名冲突
String finalPath = this.path + System.currentTimeMillis() + "." + suffixName;
Path path = Paths.get(finalPath);
Files.write(path, file.getBytes());
return "文件上传成功";
}else{
log.info("上传的文件不是图片");
return "文件类型不是图片";
}
}
}
}