当前位置:网站首页>CKEditor 4.10.1 上传图片提示“不正确的服务器响应” 问题解决
CKEditor 4.10.1 上传图片提示“不正确的服务器响应” 问题解决
2022-07-02 06:34:00 【niceyz】
最近项目采用CKEditor 4 富文本编辑器,上传图片时提示"不正确的服务器响应" , 查看官方文档要求返回json格式,官方示例:
Response: File Uploaded Successfully
上传成功返回:
{
"uploaded": 1,
"fileName": "foo.jpg",
"url": "/files/foo.jpg"
}
{
"uploaded": 1,
"fileName": "foo(2).jpg",
"url": "/files/foo(2).jpg",
"error": {
"message": "A file with the same name already exists. The uploaded file was renamed to \"foo(2).jpg\"."
}
}
Response: File Could Not Be Uploaded
上传失败返回:
{
"uploaded": 0,
"error": {
"message": "The file is too big."
}
}
地址:https://ckeditor.com/docs/ckeditor4/latest/guide/dev_file_upload.html
封装返回代码:
import java.util.HashMap;
import java.util.Map;
/**
* @description: CKEditor编辑器上传图片返回格式
* @author: yz
* @create: 2018/8/16 18:31
*/
public class FileResponse extends HashMap<String, Object> {
Map<String,Object> msgMap = new HashMap<>();
public String error(int code, String msg){
FileResponse result = new FileResponse();
msgMap.put("message",msg);
result.put("uploaded",code);
result.put("error",msgMap);
return JSONUtils.beanToJson(result);
}
public String success(int code, String fileName,String url,String msg){
FileResponse result = new FileResponse();
if(!StringUtils.isEmpty(msg)){
msgMap.put("message",msg);
result.put("error",msgMap);
}
result.put("uploaded",code);
result.put("fileName",fileName);
result.put("url",url);
return JSONUtils.beanToJson(result);
}
}上传代码:
import com.yz.common.utils.FileResponse;
import com.yz.common.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @description: 图片上传
* @author: yz
* @create: 2018/8/16 11:09
*/
@Controller
@RequestMapping("/common")
public class FileUploadController {
/*
* 图片命名格式
*/
private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmss";
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/*
* 上传图片文件夹
*/
private static final String UPLOAD_PATH = "/upload/yzimg/";
/*
* 上传图片
*/
@RequestMapping("/uploadImg")
public void uplodaImg(@RequestParam("upload") MultipartFile file,HttpServletRequest request,HttpServletResponse response) {
FileResponse fileResponse = new FileResponse();
try {
PrintWriter out = response.getWriter();
logger.info("fileSize: "+file.getSize());
// 图片大小不超过500K
if (file.getSize() > 1024*500) {
String error = fileResponse.error(0, "图片大小超过500K");
out.println(error);
return;
}
String proPath = request.getSession().getServletContext().getRealPath("/");
String proName = request.getContextPath();
String path = proPath + UPLOAD_PATH;
String fileName = file.getOriginalFilename();
String uploadContentType = file.getContentType();
String expandedName = "";
if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
expandedName = ".jpg";
} else if (uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")) {
expandedName = ".png";
} else if (uploadContentType.equals("image/gif")) {
expandedName = ".gif";
} else if (uploadContentType.equals("image/bmp")) {
expandedName = ".bmp";
} else {
String error = fileResponse.error(0, "文件格式不正确(必须为.jpg/.gif/.bmp/.png文件)");
out.println(error);
return;
}
DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
fileName = df.format(new Date()) + expandedName;
FileUtil.uploadFile(file.getBytes(), path, fileName);
String success = fileResponse.success(1, fileName, proName + "/upload/hximg/" + fileName, null);
out.println(success);
return;
} catch (Exception e) {
e.printStackTrace();
String error = fileResponse.error(0, "系统异常");
try {
response.getWriter().println(error);
return;
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
public class FileUtil {
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public static String renameToUUID(String fileName) {
return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
}
}边栏推荐
- 概念到方法,绝了《统计学习方法》——第三章、k近邻法
- oracle修改数据库字符集
- [staff] time mark and note duration (staff time mark | full note rest | half note rest | quarter note rest | eighth note rest | sixteenth note rest | thirty second note rest)
- Cartoon rendering - average normal stroke
- Chrome浏览器标签管理插件–OneTab
- Programmers with ten years of development experience tell you, what core competitiveness do you lack?
- Servlet全解:继承关系、生命周期、容器和请求转发与重定向等
- 队列管理器running状态下无法查看通道
- What is the future value of fluorite mine of karaqin Xinbao Mining Co., Ltd. under zhongang mining?
- Watermelon book -- Chapter 6 Support vector machine (SVM)
猜你喜欢

Say goodbye to 996. What are the necessary plug-ins in idea?
![[staff] common symbols of staff (Hualian clef | treble clef | bass clef | rest | bar line)](/img/ae/1ecb352c51a101f237f244da5a2ef7.jpg)
[staff] common symbols of staff (Hualian clef | treble clef | bass clef | rest | bar line)

队列管理器running状态下无法查看通道

数构(C语言)——第四章、矩阵的压缩存储(下)

Timed thread pool implements request merging

Matplotlib剑客行——容纳百川的艺术家教程

From concept to method, the statistical learning method -- Chapter 3, k-nearest neighbor method

【Go实战基础】gin 高效神器,如何将参数绑定到结构体

Data type case of machine learning -- using data to distinguish men and women based on Naive Bayesian method

C4D quick start tutorial - C4d mapping
随机推荐
Avoid breaking changes caused by modifying constructor input parameters
分布式服务架构精讲pdf文档:原理+设计+实战,(收藏再看)
Redis安装部署(Windows/Linux)
分布式锁的这三种实现方式,如何在效率和正确性之间选择?
2022/2/13 summary
ClassFile - Attributes - Code
微服务实战|Eureka注册中心及集群搭建
[staff] time mark and note duration (staff time mark | full note rest | half note rest | quarter note rest | eighth note rest | sixteenth note rest | thirty second note rest)
Solution to amq4036 error in remote connection to IBM MQ
Watermelon book -- Chapter 5 neural network
企业级SaaS CRM实现
Statistical learning methods - Chapter 5, decision tree model and learning (Part 1)
Matplotlib剑客行——容纳百川的艺术家教程
"Redis source code series" learning and thinking about source code reading
Cartoon rendering - average normal stroke
队列管理器running状态下无法查看通道
Chrome video download Plug-in – video downloader for Chrome
AMQ 4043 solution for errors when using IBM MQ remote connection
Servlet全解:继承关系、生命周期、容器和请求转发与重定向等
Pool de connexion redis personnalisé