项目所用框架为Spring+Spring Boot+Neo4j,根据所用框架在pom.xml文件中导入相应的坐标
一.application-dev.xml文件配置
upload:
#文件上传路径前缀
baseDir: src/main/resources/static/
#课程封面路径
coverDir: images/cover/
#用户头像路径
headImgDir: images/headImg/
二. WebMVCConfig.java
@Configuration
public class WebMVCConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//获取系统的根路径
String projectPath=System.getProperty("user.dir");
//映射图片保存地址
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+projectPath+"/src/main/resources/static/");
}
}
三.R.java
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("返回状态(OK:成功 ; ERROR:失败)")
private R.Status status;
@ApiModelProperty("返回code")
private Integer code;
@ApiModelProperty("返回状态描述")
private String message;
@ApiModelProperty("返回数据")
private T data;
@ApiModelProperty("时间戳")
private Long date;
public static <T> R<T> ok() {
return new R();
}
public static <T> R<T> ok(T data) {
R<T> R = new R();
R.setData(data);
return R;
}
public static <T> R<T> ok(String message, T data) {
R<T> R = new R();
R.setMessage(message);
R.setData(data);
return R;
}
public static <T> R<T> error(int code, String message) {
R<T> R = new R();
R.setStatus(Status.ERROR);
R.setCode(code);
R.setMessage(message);
return R;
}
public R() {
this.status = R.Status.OK;
this.code = PlatformCodeEnum.SUCCESS.getCode();
this.message = PlatformCodeEnum.SUCCESS.getMsg();
this.date = (new Date()).getTime();
}
public static R error() {
return error(PlatformCodeEnum.ERROR.getCode(), "未知异常,请联系管理员");
}
public static R error(String msg) {
return error(PlatformCodeEnum.ERROR.getCode(), msg);
}
public R.Status getStatus() {
return this.status;
}
public Integer getCode() {
return this.code;
}
public String getMessage() {
return this.message;
}
public T getData() {
return this.data;
}
public Long getDate() {
return this.date;
}
public void setStatus(final R.Status status) {
this.status = status;
}
public void setCode(final Integer code) {
this.code = code;
}
public void setMessage(final String message) {
this.message = message;
}
public void setData(final T data) {
this.data = data;
}
public void setDate(final Long date) {
this.date = date;
}
public String toString() {
return "R(status=" + this.getStatus() + ", code=" + this.getCode() + ", message=" + this.getMessage() + ", data=" + this.getData() + ", date=" + this.getDate() + ")";
}
public static enum Status {
OK,
ERROR;
private Status() {
}
}
}
四.FileController.java(控制器类)
@RestController
@RequestMapping("file/upload")
@Api(basePath = "file/upload", value = "文件上传控制器", description = "文件上传控制器")
public class FileController {
@Autowired
private FileService fileService;
@SysLog("上传课程封面")
@RequestMapping(method = RequestMethod.POST, value = "/uploadCourseCover")
@ApiOperation(value = "上传课程封面", notes = "上传课程封面", httpMethod = "POST")
public R uploadCourseCover(MultipartFile multipartFile){
String filePath=fileService.uploadFile(multipartFile, UploadType.COVER.getLabel());
return R.ok(filePath);
}
@SysLog("上传用户头像")
@RequestMapping(method = RequestMethod.POST, value = "/uploadUserHeadImg")
@ApiOperation(value = "上传用户头像", notes = "上传用户头像", httpMethod = "POST")
public R uploadHeadImg(MultipartFile multipartFile){
String filePath=fileService.uploadFile(multipartFile, UploadType.HEAD_IMAGE.getLabel());
return R.ok(filePath);
}
}
五.FileService.java(服务接口)
public interface FileService {
//上传文件,根据类型保存到服务器指定位置
String uploadFile(MultipartFile multipartFile, String fileType);
}
六.FileServiceImpl.java(服务实现类)
@Service
public class FileServiceImpl implements FileService {
@Value("${upload.baseDir}")
private String baseDir;
@Value("${upload.coverDir}")
private String coverDir;
@Value("${upload.headImgDir}")
private String headImgDir;
//=======================================================
// 后期如果有其他文件类型,在配置文件中添加路径,在这里注入即可
//=======================================================
//上传文件到服务器指定目录下
//根据上传的类型来更改目录
@Override
public String uploadFile(MultipartFile multipartFile, String fileType) {
String fileRealname=multipartFile.getOriginalFilename();//原始文件名
String fileName=System.currentTimeMillis() + new Random().nextInt(1000) + "_" + fileRealname;
//附件保存目录,配置文件中获取
//根据上传类型确定是哪个文件夹
String relativePath="";
if(fileType.equals(UploadType.COVER.getLabel())){
relativePath=coverDir;
}
if (fileType.equals(UploadType.HEAD_IMAGE.getLabel())){
relativePath=headImgDir;
}
//=======================================================
// 后期如果有其他文件类型,在枚举类中增加类型,在这里加判断即可
//=======================================================
String filePath=baseDir+relativePath;
//校验目录是否存在
File path=new File(filePath);
if(!path.exists()){
path.mkdirs();
}
File file=new File(filePath+fileName);
//保存文件
try {
InputStream in=multipartFile.getInputStream();
OutputStream out = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
//返回最终的相对路径
//upload前缀是配置的项目访问静态资源的路径,详见WebMVCConfig
return "upload/"+relativePath+fileName;
}
}