当前位置:网站首页>Ckeditor 4.10.1 upload pictures to prompt "incorrect server response" problem solution
Ckeditor 4.10.1 upload pictures to prompt "incorrect server response" problem solution
2022-07-02 09:37:00 【niceyz】
Recent projects have adopted CKEditor 4 Rich text editor , Prompt when uploading pictures " Incorrect server response " , Check the official documents and ask to return json Format , The official sample :
Response: File Uploaded Successfully
Upload successful return :
{
"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
Upload Failure Return :
{
"uploaded": 0,
"error": {
"message": "The file is too big."
}
}
Address :https://ckeditor.com/docs/ckeditor4/latest/guide/dev_file_upload.html
Encapsulate return code :
import java.util.HashMap;
import java.util.Map;
/**
* @description: CKEditor The editor uploads the picture and returns the format
* @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);
}
}Upload code :
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: Image upload
* @author: yz
* @create: 2018/8/16 11:09
*/
@Controller
@RequestMapping("/common")
public class FileUploadController {
/*
* Picture naming format
*/
private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmss";
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/*
* Upload picture folder
*/
private static final String UPLOAD_PATH = "/upload/yzimg/";
/*
* To upload pictures
*/
@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());
// The size of the picture does not exceed 500K
if (file.getSize() > 1024*500) {
String error = fileResponse.error(0, " The picture size exceeds 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, " The file format is not correct ( It has to be for .jpg/.gif/.bmp/.png file )");
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, " System exception ");
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 the file corresponding to the file path exists , And it's a file , Then delete
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);
}
}边栏推荐
- Redis installation and deployment (windows/linux)
- Insight into cloud native | microservices and microservice architecture
- Typora installation package sharing
- 数构(C语言)——第四章、矩阵的压缩存储(下)
- Read 30 minutes before going to bed every day_ day4_ Files
- Creation and jump of activity
- [go practical basis] how to verify request parameters in gin
- JVM instruction mnemonic
- Read Day5 30 minutes before going to bed every day_ All key values in the map, how to obtain all value values
- Learn combinelatest through a practical example
猜你喜欢

Machine learning practice: is Mermaid a love movie or an action movie? KNN announces the answer

Microservice practice | fuse hytrix initial experience

Probability is not yet. Look at statistical learning methods -- Chapter 4, naive Bayesian method

Timed thread pool implements request merging

The channel cannot be viewed when the queue manager is running

Chrome视频下载插件–Video Downloader for Chrome

上班第一天的报错(AWVS卸载不彻底)

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

每天睡前30分钟阅读Day6_Day6_Date_Calendar_LocalDate_TimeStamp_LocalTime

Operation and application of stack and queue
随机推荐
微服务实战|手把手教你开发负载均衡组件
微服务实战|原生态实现服务的发现与调用
Chrome浏览器标签管理插件–OneTab
TD联合Modelsim进行功能仿真
How to install PHP in CentOS
What are the waiting methods of selenium
How to use PHP spoole to implement millisecond scheduled tasks
Chrome浏览器插件-Fatkun安装和介绍
Chrome视频下载插件–Video Downloader for Chrome
Creation and jump of activity
Matplotlib swordsman line - first acquaintance with Matplotlib
上班第一天的报错(Nessus安装winpcap报错)
Knife4j 2. Solution to the problem of file control without selection when uploading x version files
kinect dk 获取CV::Mat格式的彩色RGB图像(openpose中使用)
Solution to amq4036 error in remote connection to IBM MQ
大学生四六级作文模板(自创版,成功跨过六级)
Knowledge points are very detailed (code is annotated) number structure (C language) -- Chapter 3, stack and queue
Knife4j 2.X版本文件上传无选择文件控件问题解决
深入剖析JVM是如何执行Hello World的
QT QLabel样式设置