jsp页面
<!-- 创建一个div粘贴图片 -->
<div class="form-group">
<label class="col-md-1 control-label" for="textarea-input">
图标:</label>
<div id="pasteShapeIcon" contenteditable="true"
style="width: 400px; height: 300px; border: dashed; margin: 3% 9.2% -0.5%">在此框中粘贴图片
</div>
</div>
<script>
//点击div框中内容清除
$("#pasteShapeIcon").click(function(){
$("#pasteShapeIcon").empty();
});
//粘贴图片
//var pasteShapeIcon=document.getElementById("pasteShapeIcon");
var pasteShapeIcon=$("#pasteShapeIcon")[0];
pasteShapeIcon.addEventListener("paste", function(event){
var clipboardData = event.clipboardData;
var file, reader;
Array.prototype.forEach.call(clipboardData.types, function(type, i){
var item = clipboardData.items[i];
var imageType = /image\/(png|jpg|webp|gif|bmp)/i;
//console.log(type, item.type, 'type');
if(type.match(imageType) || item.type.match(imageType)){
file = item.getAsFile();
reader = new FileReader();
reader.onload = function(evt){
/* console.log('result: ', evt, evt.target, evt.target.result); */
var image = new Image();
image.src = evt.target.result;
$.ajax({
//将图片url传到controller进行处理
url : "${ctx}/admin/handgesture/uploadShapeIcon.json",
type : "post",
cache : false,
dataType:"text",
/* async:false ajax按顺序执行fangfa */
async:false,
data :{'shapeIconPaste':image.src,
'code':$("#code").val()
},
success : function(url) {
//将返回的图片存储地址赋在页面input中,随form表单传到后台保存
$("#shapeIconPaste").val(url);
}
});
pasteShapeIcon.appendChild(image);
};
reader.readAsDataURL(file);
}
});
}, false);
//controller
工具类
package com.shiro.entity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Decoder;
public class FileUploadUtil {
public static String UPLOAD_DIR="upload";
public static final String BASE_DIR=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
.getRequest().getSession().getServletContext().getRealPath("/")+UPLOAD_DIR;
public static final String RL_DIR=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
.getRequest().getContextPath();
public static final String UPLOAD_PIC_FILE_DIR = BASE_DIR + File.separator+"backpic";
public static final String UPLOAD_APP_FILE_DIR = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession().getServletContext().getRealPath("/")+"app";
public static final String UPLOAD_USER_FILE_DIR = BASE_DIR + File.separator+"hand";
public static final String UPLOAD_ADS_FILE_DIR = BASE_DIR + File.separator+"sysads";
public static final String UPLOAD_EXCEL_FILE_DIR = BASE_DIR + File.separator+"excel";
public static final String UPLOAD_OTA_FILE_DIR = BASE_DIR + File.separator+"ota";
public static Log log = LogFactory.getLog(FileUploadUtil.class);
//base64字符串转化成图片
public static String GenerateImage(String imgStr,String absolutePath,String code)
{
File dirs = new File(absolutePath);
dirs.mkdirs();
//截取图片后缀名
String extName=imgStr.substring(11, 14);
String fileName=code+"_"+System.currentTimeMillis()+"."+extName;
//对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) //图像数据为空
return null;
BASE64Decoder decoder = new BASE64Decoder();
//得到的base64 字符串为截掉,之前的内容
String[] imgurl=imgStr.split(",");
try
{ File saveFile = new File(absolutePath,fileName);
if(!saveFile.exists()){
saveFile.createNewFile();
}
//Base64解码
byte[] b = decoder.decodeBuffer(imgurl[1]);
//生成jpeg图片
// String imgFilePath = saveFile.getPath();//新生成的图片
OutputStream out = new FileOutputStream(saveFile);
out.write(b);
out.flush();
out.close();
log.info("Upload success :"+saveFile.getAbsolutePath());
String dl=File.separator+UPLOAD_DIR+absolutePath.split(UPLOAD_DIR)[1];
return joinPath(new String[]{dl,fileName});
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static String joinPath(String[] subPaths){
return StringUtils.join(subPaths,File.separator);
}
}
controller ajax处理的base64 url,返回存储的图片地址
@ResponseBody
@RequestMapping(value = "/uploadShapeIcon.json")
public String uploadShapeIcon(HttpServletResponse response, @RequestParam String shapeIconPaste, @RequestParam String code,Model model,HttpServletRequest request){
String url="";
response.setCharacterEncoding("UTF-8");
try {
//获取粘贴板图片
String absolutePath = FileUploadUtil.joinPath(new String[] { FileUploadUtil.UPLOAD_USER_FILE_DIR});
url=FileUploadUtil.GenerateImage(shapeIconPaste, absolutePath, code);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return url;
}