@Data
public class UploadFileVO {
private String src;
private String title;
}
@Data
public class JsonResult<T> {
private Integer code;
private String msg;
private T data;
public JsonResult(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public JsonResult() {
}
public JsonResult fail() {
return new JsonResult(1, "操作失败", null);
}
public JsonResult fail(String msg) {
return new JsonResult(1, msg, null);
}
public JsonResult ok() {
return new JsonResult(0, "操作成功", null);
}
public JsonResult ok(T data) {
return new JsonResult(0, "操作成功", data);
}
}
import com.ssm.blog.dto.JsonResult;
import com.ssm.blog.dto.UploadFileVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Calendar;
@Slf4j
@Controller
@RequestMapping("/admin/upload")
public class UploadFileController {
public final String rootPath="G:/Github/ForestBlog/uploads";
public final String allowSuffix=".bmp.jpg.jpeg.png.gif.pdf.doc.zip.rar.gz";
@RequestMapping(value = "/img", method = RequestMethod.POST)
@ResponseBody
public JsonResult uploadFile(@RequestParam("file") MultipartFile file) {
String filename = file.getOriginalFilename();
String name = filename.substring(0, filename.indexOf("."));
String suffix = filename.substring(filename.lastIndexOf("."));
if (allowSuffix.indexOf(suffix) == -1) {
return new JsonResult().fail("不允许上传该后缀的文件!");
}
Calendar date = Calendar.getInstance();
File dateDirs = new File(date.get(Calendar.YEAR)
+ File.separator + (date.get(Calendar.MONTH) + 1));
File descFile = new File(rootPath + File.separator + dateDirs + File.separator + filename);
int i = 1;
String newFilename = filename;
while (descFile.exists()) {
newFilename = name + "(" + i + ")" + suffix;
String parentPath = descFile.getParent();
descFile = new File(parentPath + File.separator + newFilename);
i++;
}
if (!descFile.getParentFile().exists()) {
descFile.getParentFile().mkdirs();
}
try {
file.transferTo(descFile);
} catch (Exception e) {
e.printStackTrace();
log.error("上传失败,cause:{}", e);
}
String fileUrl = "/uploads/" + dateDirs + "/" + newFilename;
UploadFileVO uploadFileVO = new UploadFileVO();
uploadFileVO.setTitle(filename);
uploadFileVO.setSrc(fileUrl);
return new JsonResult().ok(uploadFileVO);
}
}