SpringBoot2.X整合UEditor上传图片到OSS服务 远程上传图片-Java版本

1,UEditor的请求全部是通过ueditor.config.js文件的serverUrl变量"/config"接口调用的。在"/config"接口中判断action是否为uploadimage类型,表示为上传图片,在if块中写远程上传图片的代码。

本人这里使用的springcloud的feign远程调用,feign上传文件报FileUploadException: the request was rejected because no multipart boundary was found异常,请参考:Springcloud配置Feign文件上传支持_hlp4207的博客-CSDN博客

使用httpclient的请参考:HttpClient上传文件传入MultipartFile类型_lsqingfeng的博客-CSDN博客

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import com.familylinkedu.common.support.JsonResult;
import com.familylinkedu.web.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 百度富文本编辑器
 *
 * @author lixx
 * @version 1.0
 * @date 2020-05-06 14:18
 */
@RestController
public class UEditorController {

	@Autowired
	private UploadService uploadService;

	@RequestMapping(value = "/config")
	public void config(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		String action = request.getParameter("action");
		if ("uploadimage".equals(action)) {
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartHttpServletRequest.getFile("file");
			if(null == file || StringUtils.isBlank(file.getOriginalFilename())){
				writer.write("{'state':'文件不能为空'}");
			}
			// 原来的文件名
			String originalName = file.getOriginalFilename();
			// 文件后缀
			String suffix = originalName.substring(originalName.indexOf("."));
			JsonResult jsonResult = uploadService.updateImage(file);
			if (jsonResult.getCode().equals(0)) {
				Map<String, String> resultMap = JSONObject.parseObject(JSONObject.toJSONString(jsonResult.getData()), Map.class);
				Map<String, String> map = new HashMap<>(7);
				map.put("state", resultMap.get("status"));
				map.put("original", originalName);
				map.put("size", resultMap.get("size"));
				map.put("type", suffix);
				map.put("url", resultMap.get("path"));
				String json = JSON.toJSONString(map);
				writer.write(json);
			} else {
				writer.write("{'state':'上传失败'}");
			}
		} else {
			response.setContentType("application/json");
			// rootPath路径: /D:/develop/web-service/target/classes/static/ueditor/jsp, 上传的图片会在这里路径下面
			String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/ueditor/jsp";
			writer.write(new ActionEnter(request, rootPath).exec());
		}
		writer.flush();
		writer.close();
	}
}

返回的json格式请参考:

{
    "state": "SUCCESS",    // 成功
    "original": "77426e62c700605da38a24f1dd495a55.jpg",// 原文件名
    "size": "21382",    // 文件大小
    "title": "1589078472007085896.jpg", // 新文件名
    "type": ".jpg",    // 文件后缀
    "url": "http://www.baidu.com/upload/image/20200510/1589078472007085896.jpg"    // 文件路径
}

2,把config.json的imageUrlPrefix变量置空。

3,注意点上传图片接口的变量名称一定要与config.json文件中的imageFieldName变量值一致,不然会报Required request part '***' is not present异常。

4,看下运行效果。 

5,SpringBoot整合UEditor请参考上一篇博客:SpringBoot 2.X整合UEditor百度富文本编辑器-Java版本_又逢乱世-CSDN博客 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
在Spring中实现UEditor图片上传可以参考以下步骤: 1. 在前端Vue代码中配置UEditor富文本编辑器,并对上传图片做出相关设置。 2. 在Spring后端代码中编写图片上传的控制器,处理前端传递的图片文件信息。 3. 在Spring配置文件中配置文件上传的相关参数。 下面是具体的实现方法: 1. 前端代码: 在Vue组件中引入UEditor富文本编辑器,可以使用UEditor官网提供的Vue UEditor Wrapper组件。并在UEditor配置项中设置上传图片的相关参数,如下所示: ``` <template> <div> <vue-ueditor-wrap v-model="content" :config="ueditorConfig" :z-index="100" ></vue-ueditor-wrap> </div> </template> <script> import VueUeditorWrap from 'vue-ueditor-wrap'; export default { components: { VueUeditorWrap }, data () { return { content: '', ueditorConfig: { UEDITOR_HOME_URL: '/static/UEditor/', serverUrl: '/api/upload', maximumWords: 50000, initialFrameWidth: '100%', initialFrameHeight: 500, autoHeightEnabled: false, autoFloatEnabled: false, toolbars: [ ['source', 'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'forecolor', 'backcolor', 'fontfamily', 'fontsize', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', 'touppercase', 'tolowercase', 'link', 'unlink', 'insertimage', 'emotion', 'scrawl', 'music', 'insertvideo', 'attachment', 'map', 'gmap', 'insertcode', 'template', 'background', 'date', 'time', 'spechars', 'searchreplace', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts' ] ] }, }; }, }; </script> ``` 在上述代码中,通过`serverUrl`参数设置了上传图片的后端接口地址为`/api/upload`。 2. 后端控制器代码: 在Spring中,可以通过编写一个控制器方法来实现UEditor上传图片的功能。具体代码如下: ``` @RequestMapping(value = "/api/upload", method = RequestMethod.POST) @ResponseBody public String uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf-8"); response.setHeader("Content-Type", "text/html"); String rootPath = request.getSession().getServletContext().getRealPath("/"); String contextPath = request.getContextPath(); String basePath = rootPath + File.separator + "upload" + File.separator; String savePath = contextPath + "/upload/"; String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"}; String upfile = "upfile"; JSONObject result = new JSONObject(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator<String> iterator = multipartRequest.getFileNames(); while (iterator.hasNext()) { MultipartFile file = multipartRequest.getFile(iterator.next()); if (file != null) { String fileName = file.getOriginalFilename(); String fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); boolean isAllow = false; for (String ext : fileType) { if (ext.equals(fileExt)) { isAllow = true; break; } } if (!isAllow) { result.put("state", "不支持的文件类型!"); return result.toJSONString(); } String newFileName = UUID.randomUUID().toString() + fileExt; File uploadedFile = new File(basePath, newFileName); if (!uploadedFile.getParentFile().exists()) { uploadedFile.getParentFile().mkdirs(); } file.transferTo(uploadedFile); result.put("state", "SUCCESS"); result.put("url", savePath + newFileName); result.put("title", newFileName); result.put("original", fileName); result.put("type", fileExt); result.put("size", file.getSize()); } } return result.toJSONString(); } ``` 3. Spring配置文件: 在Spring的配置文件中,需要配置文件上传的相关参数。具体代码如下: ``` <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> <property name="defaultEncoding" value="UTF-8"/> <property name="resolveLazily" value="true"/> </bean> ``` 其中,`maxUploadSize`参数设置了上传文件的最大大小,单位为字节。 至此,我们就完成了在Spring+Vue中实现UEditor图片上传的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又逢乱世

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值