1. 程式人生 > >CKEditor 4.10.1 上傳圖片提示“不正確的伺服器響應” 問題解決

CKEditor 4.10.1 上傳圖片提示“不正確的伺服器響應” 問題解決

最近專案採用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);
   }
}