最近写项目中需要用到LayUI富文本编辑器,其他地方都挺好,唯独上传图片时,要不就是上传完成后回显404,要不就是访问时404(访问时我是新打开的一个页面),返回路径一直有问题,之后把返回的路径改成绝对路径就可以。
效果图如下:
先添加上传图片接口,layui会自动传递参数,后台直接写对应的上传方法就行了。
var layedit = layui.layedit;
layedit.set({ //设置图片接口
uploadImage: {
url: 'layUITextarea/upload', //接口url
type: 'post'
}
});
后台上传完成后需要返回四个参数,layui自定义接收显示(不返回图片无法显示)
layui前台接收返回的数据格式为:
{
"code": 0, //0表示成功,其他表示失败
"msg": "", //提示信息,//一般上传失败后返回
"data": {
"src": "图片路径",
"title": "图片名称" //可选
}
}
所以后台返回需要返回这几个参数
//上传
@RequestMapping(value="/upload")
@ResponseBody
public Object upload(MultipartFile file) {
String filename = file.getOriginalFilename();
String uuid = UUID.randomUUID().toString();
//上传的方法在Service层写的,这里直接调用的
boolean boole = pService.savefile(file, uuid);
if (boole) {
Map<String,Object> map = new HashMap<String,Object>();
Map<String,Object> map2 = new HashMap<String,Object>();
map.put("code", 0); //0表示上传成功
map.put("msg","上传成功"); //提示消息
//src返回图片上传成功后的下载路径,这里直接给绝对路径
map2.put("src", "http://localhost/layUITextarea/download?uuid="+uuid);
map2.put("title", filename);
map.put("data", map2);
return map;
} else {
return new AjaxResult(true, file.getOriginalFilename());
}
}
//下载方法
@RequestMapping(value = "/download")
@ResponseBody
private void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
fileService.download(uuid, request, response);
}
Service层上传下载部分代码。
@Service
public class FileService extends CommonService<FileImg, Integer> {
@Autowired
private FileRepository fileRepository;
// 图片存放位置
private final static String IMAGEPATH="e:\\layui\\image";
//保存图片
@Transactional
public boolean savefile(MultipartFile file, String uuid){
try{
File path = path(file.getContentType());
String filename = file.getOriginalFilename();
FileImg fileEntity = new FileImg();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=new Date();
fileEntity.setFileName(filename);
fileEntity.setUuid(uuid);
String storeaddress = path.getAbsolutePath();
fileEntity.setStoreaddress(storeaddress);
File saveFile = new File(path,uuid);
try {
fileRepository.save(fileEntity);
file.transferTo(saveFile);
return true;
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
return false;
}
}catch (Exception e){
System.out.println("图片保存异常");
return false;
}
}
//图片地址是否存在
private File path(String filename) {
File pat=new File("e:\\layui");
File path = new File(FileService.IMAGEPATH);
if(!pat.isDirectory()) {
pat.mkdir();
}
if(!path.isDirectory()) {
path.mkdir();
}
return path;
}
/**
* 下载
* @param uuid
* @param request
* @param response
*/
public void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
FileImg fileentity = fileRepository.findByUuid(uuid);
String filename = fileentity.getFileName();
filename = getStr(request, filename);
File file = new File(fileentity.getStoreaddress(), uuid);
if(file.exists()) {
FileInputStream fis;
try {
fis = new FileInputStream(file);
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment; filename=" + filename );
ServletOutputStream out = response.getOutputStream();
byte[] buf=new byte[2048];
int n=0;
while((n=fis.read(buf))!=-1){
out.write(buf, 0, n);
}
fis.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getStr(HttpServletRequest request, String fileName) {
String downloadFileName = null;
String agent = request.getHeader("USER-AGENT");
try {
if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
//downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
//设置字符集
downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
}else{
downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return downloadFileName;
}
}
后台返回src路径时最好加绝对路径,不然添加访问时图片路径会404
关于layui富文本域form表单提交和ajax提交可以访问:https://blog.csdn.net/qq_40205116/article/details/89433623
layui富文本域完整案例:https://blog.csdn.net/qq_40205116/article/details/89536834