Ueditor (3): Upload pictures to a directory outside the project

Ueditor's image upload is uploaded to the project by default, and the directory where the project is located is passed in through application.getRealPath( "/" ) in controller.jsp. Unfortunately, this directory cannot be changed. After changing it, a very common problem will occur - the back- end configuration items are not loaded normally, and the uploading plug-in cannot be used normally , because this directory needs to be used to find the paths of configuration files and other files.

So if you want to upload the image to the outside of the project, you can only modify the source code.

 

There are many ways to change. What I use here is to add an attribute to the config.json file, and then read it in the background. The specific steps and codes are as follows:

1. Add properties at the end of the config.json file :

"outsideSavePath":"D:/bfp"/*The external link of the project is under the project by default. After configuring this field, it can be configured outside the project*/

There are two points to note here:

a. Add a comma at the end of the previous attribute

b. When adding comments, you must use the form of /**/. If you use other comment forms such as //, an error will be reported. The error is also that the classic back-end configuration item is not loaded normally, and the uploading plugin cannot be used normally.

 

2. Add the read of this property in the getConfig (int type) method of ConfigManager.java :

conf.put("outsideSavePath",this.jsonConfig.getString( "outsideSavePath"));//项目外部路径
conf.put( "savePath", savePath );
conf.put( "rootPath", this.rootPath );
return conf;

What I have here is outsideSavePath

 

3. Read this property in the save() method of BinaryUploader.java where the image is uploaded :

String physicalPath="";
 //If there is a specified external configuration path, use the external configuration path, otherwise use the internal project path
if(conf.get("outsideSavePath")!=null && conf.get("outsideSavePath").toString ().trim().length()>0){
      physicalPath = (String) conf.get("outsideSavePath") + savePath;
      savePath = physicalPath;//Return the absolute physical path
}else{
      //Inside the project, Return the relative physical path
      physicalPath = (String) conf.get("rootPath") + savePath;
}

The complete code for this method is as follows:

public static final State save(HttpServletRequest request,
		Map<String, Object> conf) {
	FileItemStream fileStream = null;
	boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

	if (!ServletFileUpload.isMultipartContent(request)) {
		return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
	}

	ServletFileUpload upload = new ServletFileUpload(
			new DiskFileItemFactory());

    if ( isAjaxUpload ) {
        upload.setHeaderEncoding( "UTF-8" );
    }

	try {
		FileItemIterator iterator = upload.getItemIterator(request);

		while (iterator.hasNext()) {
			fileStream = iterator.next();

			if (!fileStream.isFormField())
				break;
			fileStream = null;
		}

		if (fileStream == null) {
			return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
		}

		String savePath = (String) conf.get("savePath");
		String originFileName = fileStream.getName();
		String suffix = FileType.getSuffixByFilename(originFileName);

		originFileName = originFileName.substring(0,
				originFileName.length() - suffix.length());
		savePath = savePath + suffix;

		long maxSize = ((Long) conf.get("maxSize")).longValue();

		if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
			return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
		}

		savePath = PathFormat.parse(savePath, originFileName);
		String physicalPath="";
		//If there is a specified external configuration path, use the external configuration path, otherwise use the internal project path
		if(conf.get("outsideSavePath")!=null && conf.get("outsideSavePath").toString().trim().length()>0){
			physicalPath = (String) conf.get("outsideSavePath") + savePath;
			savePath = physicalPath;//Return the absolute physical path
		}else{
			//In the project, return the relative physical path
			physicalPath = (String) conf.get("rootPath") + savePath;
		}
		//System.out.println("File upload path: "+physicalPath);
		InputStream is = fileStream.openStream();
		State storageState = StorageManager.saveFileByInputStream(is,physicalPath, maxSize);
		is.close();

		if (storageState.isSuccess()) {
			storageState.putInfo("url", PathFormat.format(savePath));
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", originFileName + suffix);
		}

		return storageState;
	} catch (FileUploadException e) {
		e.printStackTrace ();
		return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
	} catch (IOException e) {
		e.printStackTrace ();
	}
	return new BaseState(false, AppInfo.IO_ERROR);
}

In the source code, in addition to BinaryUploader.java, which can upload pictures/files, Base64Uploader.java can also implement this function. As for when to use the two methods, I have not done any research, so I added this code to both methods. Of course, the image uploader uses BinaryUploader.java.

The modified source code and the jar made from the source code have been uploaded to the attachment and can be downloaded if necessary.

(PS: All the catches in the original source code do not have printStackTrace(), so no matter what the system reports, there will be no prompts. I have suffered from this, so I added it to each catch in the source code. printStackTrace(), and hit the jar package. Do not download if you mind )

 

4. Modify the display mode of the page :

According to the previous idea: the path under the project is returned, and the src of the img tag can display the picture directly by using the path. But this has been changed to the absolute physical path on the server, and the previous path will never be displayed. There are many ways to display pictures, I use the project plug-in method here. For specific plug-in steps, please refer to javaweb using virtual directory to display image information under non-project files

After the image is uploaded, it will enter the function unhtmlData(imgCi) { method in ueditor.all.js. I have not done much research on its specific process, but I intercepted it when splicing the html code. The modified code is as follows:

var img_src = ci.src;
var widthStyle = "";
 if(img_src.indexOf("http://")!=-1 || img_src.indexOf("https://")!=-1){//表情符号
      var width = getImgWidth(img_src);
      widthStyle="style=\"width:"+width+"px;height:"+width+"px;\"";
 }else{
       img_src = formatImgSrc(img_src);
}
str = '<img '+widthStyle+' src="' + img_src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') 。。。。

The specific code is as follows:

if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
    var first = opt.shift();
    var floatStyle = first['floatStyle'];
    delete first['floatStyle'];
    domUtils.setAttributes(img, first);
    me.execCommand('imagefloat', floatStyle);
    if (opt.length > 0) {
        range.setStartAfter(img).setCursor(false, true);
        me.execCommand('insertimage', opt);
    }

} else {
    var html = [], str = '', ci;
    ci = eight [0];
    if (opt.length == 1) {
        unhtmlData(ci);
        var img_src = ci.src;
        var widthStyle = "";
        if(img_src.indexOf("http://")!=-1 || img_src.indexOf("https://")!=-1){//表情符号
			var width = getImgWidth(img_src);
			widthStyle="style=\"width:"+width+"px;height:"+width+"px;\"";
		}else{
			img_src = formatImgSrc(img_src);
		}
        str = '<img '+widthStyle+' src="' + img_src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
            (ci.width ? 'width="' + ci.width + '" ' : '') +
            (ci.height ? ' height="' + ci.height + '" ' : '') +
            (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
            (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
            (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
            (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
            (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
            (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
        if (ci['floatStyle'] == 'center') {
            str = '<p style="text-align: center">' + str + '</p>';
        }
        html.push(str);
    } else {
        for (var i = 0; ci = opt [i ++];) {
            unhtmlData(ci);
            var img_src = formatImgSrc(ci.src);
            str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + img_src + '" ' +
                (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
                (ci.height ? ' height="' + ci.height + '" ' : '') +
                ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
                (ci.border || '') + '" ' +
                (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
            html.push(str);
        }
    }
    me.execCommand('insertHtml', html.join(''));
}

PS: The code for for is useful when uploading multiple images, the previous code for uploading a single image or using expressions

The two js methods used are as follows:

//Get the basic information of the url
function getURLInfo(){
	var projectName="";//Project name
	projectName = window.location.pathname;// /XXX/XXXX!XXX.action
	projectName = projectName.substring(1,(projectName.substring(1).indexOf("/")+1));//Get the location of the second/

	//protocol: http
	//host 127.0.0.1:8090
	host_URL = window.location.protocol+"//"+window.location.host;
	project_URL = host_URL+"/"+projectName;
}

//According to the picture or file saved under the project or not under the project to determine the display mode of the picture
function formatImgSrc(img_src){
	if(img_src.indexOf(":")!=-1){//The directory outside the project for description, then use the plug-in form to access the picture
		img_src = host_URL+img_src.substring(2);
	}else{//Use the normal way
		img_src=project_URL+img_src;
	}
	return img_src;
}

The main function is to add project information to the src of img, which becomes similar to: http://192.168.0.100:8080/test/ueditor/20170531/img_12346799.jpg or: http://192.168.0.100:8080/bfp/ueditor /20170531/img_12346799.jpg directory.

Note: This directory will be saved in the database, and the specific path above will also be displayed when the page is accessed .

 

Finally, there is an auxiliary method. The specific purpose is related to the problem to be discussed in the next article. Here is the code to ensure completeness:

/**
 * This method returns the rough size of the picture according to the folder where the expression package is located to solve the problem that the expression is stretched on the mobile phone
 * **/
function getImgWidth(img_src){
	var width = 0;
	var bbb = img_src.substr(img_src.lastIndexOf('/', img_src.lastIndexOf('/') - 1) + 1);
	var emotion = bbb.substr(0,bbb.indexOf("/"));//expression package folder
	switch(emotion){
		case "babycat"://baby猫
		case "bobo"://BOBO (most are 50x50, a few are other sizes)
		case "ldw"://mung bean frog
		case "tsj"://Tusky
			width=50;break
		case "face"://bubble expression
			width=25;break;
		case "youa"://yes
			width=60;break;
		case "jx2"://recommended
			var ddd = bbb.substr(bbb.indexOf("/")+3,4);//Name serial number
			ddd = parseInt(ddd);
			//Tusky, mung bean frog, bobo, baby cat
			if(ddd<=56){width=50;
			}else if(ddd>=71){//Yes
				width=60;
			}else{//Bubble expression
				width=25;
			}
			break;
	}
	return width;
}

So far, "Uploading pictures to a directory outside the project" is completed, I hope it will be helpful to everyone. Come on, everybody!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326444297&siteId=291194637