---
title: "UEditor Java 上传图片配置"
author: "xlaohe1"
date: "2014-06-16T22:55:09Z"
tags: []
categories: ["Web前端"]
slug: "ueditor-java"
draft: false
lastmod: "2014-06-16T22:55:09Z"
id: 2080720
url: "https://namas.iteye.com/blog/2080720"
---

不使用默认的ueditor-mini.jar进行上传，自定义上传
关于UEditor的搭建我这里就不用细说了，这个官网的例子很详细
这里只说配置上传，使用的springmvc
首先找到umeditor.config.js，找到下面这样的代码

```js

 //为编辑器实例添加一个路径，这个不能被注释
        UMEDITOR_HOME_URL : URL

        //图片上传配置区
        ,imageUrl:URL+"jsp/imageUp.jsp"             //图片上传提交地址
        ,imagePath:URL + "jsp/"                     //图片修正地址，引用了fixedImagePath,如有特殊需求，可自行配置   
        ,imageFieldName:"upfile"                   //图片数据的key,若此处修改，需要在后台对应文件修改对应参数


```

现在来说一下上面的参数：
URL，这里指向的是你项目的ueditor文件夹
比如我的umeditor.js放在项目webroot/ueditor/umeditor.js这里，那么URL就是
HTTP://ip:port/webname/ueditor/，
当然具体的地址要根据你的配置文件而定
其中的imageFieldName:"upfile"这里的upfile就是<input type="file" name="upfile"/>这个upfile很重要，后台的数据就靠它获得，你这里修改了后台也要做相应处理
然后把上面的代码修改成指向自己写的contorller


```js

 //为编辑器实例添加一个路径，这个不能被注释
        UMEDITOR_HOME_URL : URL

        //图片上传配置区
        ,imageUrl:root+"/upload/img"             //图片上传提交地址
       // ,imageUrl:URL+"jsp/imageUp.jsp"             //图片上传提交地址
       // ,imagePath:URL + "jsp/"                     //图片修正地址，引用了fixedImagePath,如有特殊需求，可自行配置
// 这里的imagePath就是下面的_file方法
// 其路径是root/upload/file/+result.url，result是上传返回的json
         ,imagePath:root + "/upload/file/"   
        ,imageFieldName:"upfile"                   //图片数据的key,若此处修改，需要在后台对应文件修改对应参数


```


里面的root是项目的根路径
/upload/img就是后台的controller处理地址
/upload/file/也是后台的处理地址，这个这里有一点要注意，我在controller里说明
接下来是/upload/img的controller

```java

/**
* @upfile 就是上面提到的upfile，要对应一致
*/
@RequestMapping("/upload/img")
	@ResponseBody
	public String upload(@RequestParam("upfile") MultipartFile upfile,HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String result = "";
		if(path == null) {
			System.out.println(">> the get file path error!");
			return result;
		}
		FileOutputStream out = null; 
		try {
			// 存放路径，如果不存在则创建路径
			File file = new File(rootPath);
			if(!file.exists()) file.mkdirs();
			// 随机生成文件名，oname是原始文件名称
			String fname = randomName(), 
				   oname = upfile.getOriginalFilename();
			out = new FileOutputStream(rootPath + "/" + fname);
			out.write(upfile.getBytes());
			out.close(); 
			//{"name":"10571402926855858.jpg", "originalName": "china.jpg", "size": 43086, "state": "SUCCESS", "type": ".jpg", "url": "upload/20140616/10571402926855858.jpg"}
			// result返回的url参照IndexController._file方法
			result = "{\"name\":\""+ fname +"\", \"originalName\": \""+ oname +"\", \"size\": "+ upfile.getSize() +", \"state\": \"SUCCESS\", \"type\": \""+FileUtils.getExt(oname)+"\", \"url\": \""+path + "_" + fname+"\"}";
			result = result.replaceAll( "\\\\", "\\\\" );
		} catch(Exception e) {
		} finally {
			out.close();
		}

		return result;
	}



```


这就是上传的controller处理方法，里面只有2点注意：
1）就是result的返回格式，可以参照官方的例子
2）就是result返回的url，这个具体说明请往下看

```java

/**
	 * 获得图片
	 * @param path 图片路径：140615_xxx，格式为:datedir_filename
	 * @param request
	 * @param response
	 */
@RequestMapping(value = "/file/{path}")
	public @ResponseBody
	void _file(@PathVariable String path, HttpServletRequest request, HttpServletResponse response) {
                // 这个path就是上面result的url
                // 因为我是多层目录所以就使用了_下划线代替/
                // 主要就是注意路径要对应一致就行了
		path = path.replaceAll("_", "/");
		FileInputStream in = null;
		OutputStream out = null;
		try {
			File file = new File(rootPath + path);
			in = new FileInputStream(file);
			byte[] b = new byte[(int) file.length()];
			in.read(b);
			in.close();
			response.setContentType("image/*");
			out = response.getOutputStream();
			out.write(b);
			out.flush();
			out.close();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

```