使用kindeditor批量上传图片失败

忘川y 忘川y 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
上传图片时 将图片静态存储在nginx服务器中,但是nginx里存在资源,却显示上传失败,但是也有响应信息,请求路径也返回200
下面是后台代码
/**
* 图片上传
*/
@Controller

public class PicUploadController {

private static final Logger LOGGER = LoggerFactory.getLogger(PicUploadController.class);

@Autowired
private PropertieService propertieService;

private static final ObjectMapper mapper = new ObjectMapper();

// 允许上传的格式
private static final String[] IMAGE_TYPE = new String[] { ".bmp", ".jpg", ".jpeg", ".gif", ".png" };

@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletResponse response)
throws Exception {

// 校验图片格式
boolean isLegal = false;
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
isLegal = true;
break;
}
}

// 封装Result对象,并且将文件的byte数组放置到result对象中
PicUploadResult fileUploadResult = new PicUploadResult();

// 状态,0-合法,1-不合法
fileUploadResult.setError(isLegal ? 0 : 1);

// 文件新路径
String filePath = getFilePath(uploadFile.getOriginalFilename());

if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Pic file upload .[{}] to [{}] .", uploadFile.getOriginalFilename(), filePath);
}

// 生成图片的绝对引用地址
String picUrl = StringUtils.replace(
StringUtils.substringAfter(filePath, propertieService.REPOSITORY_PATH), "\\", "/");
fileUploadResult.setUrl(propertieService.IMAGE_BASE_URL + picUrl);


File newFile = new File(filePath);

// 写文件到磁盘
uploadFile.transferTo(newFile);

// 校验图片是否合法
isLegal = false;
try {
BufferedImage image = ImageIO.read(newFile);
if (image != null) {
fileUploadResult.setWidth(image.getWidth() + "");
fileUploadResult.setHeight(image.getHeight() + "");
isLegal = true;
}
} catch (IOException e) {
}

// 状态
fileUploadResult.setError(isLegal ? 0 : 1);

if (!isLegal) {
// 不合法,将磁盘上的文件删除
newFile.delete();
}

//设置响应内容的类型,文本类型
response.setContentType("text/html");
String json=mapper.writeValueAsString(fileUploadResult);//将java对象转换为json字符串
System.out.println(json);
return json;
}

private String getFilePath(String sourceFileName) {
String baseFolder = propertieService.REPOSITORY_PATH + File.separator + "images";
Date nowDate = new Date();
// yyyy/MM/dd
String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy")
+ File.separator + new DateTime(nowDate).toString("MM") + File.separator
+ new DateTime(nowDate).toString("dd");
File file = new File(fileFolder);
if (!file.isDirectory()) {
// 如果目录不存在,则创建目录
file.mkdirs();
}
// 生成新的文件名
String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
+ RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
return fileFolder + File.separator + fileName;
}

}
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
忘川y
Web 开发 81,108 成员 341,721 内容