版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zwl18210851801/article/details/83183790
controller类:
package com.xinjian.znxj.modules.webapi.V1;
import com.xinjian.znxj.common.entity.R;
import com.xinjian.znxj.modules.image.entity.ZnxjPictureEntity;
import com.xinjian.znxj.modules.image.service.ZnxjPictureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
import static com.xinjian.znxj.common.utils.ShiroUtils.getUserId;
@RestController
@RequestMapping("/api/v1/images")
@Api(value = "图片接口", description = "图片接口")
public class ImageController {
@Value("${app.ftp.base}")
private String basePath;
@Autowired
private ZnxjPictureService znxjPictureService;
@PostMapping(value = "/upload",consumes = "multipart/*",headers = "content-type=multipart/form-date")
@ApiOperation(value="文件上传", notes="文件上传")
public R upload(@ApiParam(value = "上传的文件" ,required = true) MultipartFile file, HttpServletRequest request){
long fileSize = file.getSize();
Map<String,Object> map = new HashMap<>();
if (file.isEmpty()) {
return R.error(101,"文件为空");
} else if (fileSize > (10 * 1024 * 1024)) {
return R.error(101,"文件过大");
} else {
// 获取文件名
String fileName = file.getOriginalFilename();
String oldFileName = fileName;
// 获取文件的后缀名
String extensionFileName = fileName.substring(fileName.lastIndexOf("."));
Long userID = getUserId();
//获取当前系统时间戳
String dateStr=System.currentTimeMillis()+"";
// 文件上传后的路径拼接
String filePath=basePath+"/"+userID+"/"+dateStr+extensionFileName;
// 上传文件
File dest = new File(filePath);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
String fileUrl="/img"+filePath.replace(basePath,"");
String id = UUID.randomUUID().toString();
ZnxjPictureEntity fileEntity = new ZnxjPictureEntity();
fileEntity.setPictureid(id);
fileEntity.setPictureaddr(fileUrl);
fileEntity.setCreatedate(new Date());
fileEntity.setCreateuser(getUserId()+"");
fileEntity.setRemarks(oldFileName);
fileEntity.setDelflag(0);
R result=znxjPictureService.saveZnxjPicture(fileEntity);
if("200".equals(String.valueOf(result.get("code")))){
map.put("id",id);
map.put("url",fileUrl);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return R.result(200,"success",map);
}
}
swagger接口效果: