前端页面:
<textarea class="scroll" id="text" placeholder="在此输入..."></textarea>
<script type="text/javascript">
document.querySelector("#text").addEventListener("paste", function(e){
//添加监听paste事件
var cbd = e.clipboardData;
var ua = window.navigator.userAgent;
if ( !(e.clipboardData && e.clipboardData.items) ) {
return ;
}
if(cbd.items && cbd.items.length === 2 && cbd.items[0].kind === "string" && cbd.items[1].kind === "file" && cbd.types && cbd.types.length === 2 && cbd.types[0] === "text/plain" && cbd.types[1] === "Files" && ua.match(/Macintosh/i) && Number(ua.match(/Chrome/(d{2})/i)[1]) < 49){
return;
}
for(var i = 0; i < cbd.items.length; i++) {
var item = cbd.items[i];
if(item.kind == "file"){
var blob = item.getAsFile();
if (blob.size === 0) {
return;
}
var data = new FormData();
data.append("blob", blob);
$.ajax({
url : "/user/uploads",
type : 'POST',
cache : false,
data : data,
processData : false,
contentType : false,
success : function(result){
if(result.state == "1"){
console.log(result.msg)
var html = "<img src='"+result.fileAddress+"' width='200' height='200'>";
$("#text").val(html);
$("#submit").trigger("click"); //模拟点击按钮,粘贴之后直接发送
}else if(result.state == "2"){
console.log(result.msg)
}else if(result.state == "3"){
console.log(result.msg)
}
}
});
}
}
}, false)
</script>
后端上传方法:
@RequestMapping(value="/uploads",produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
@ResponseBody
public String uploads(@RequestParam(value = "blob", required = false) MultipartFile blob, HttpServletRequest request){
/**
* 入参直接写MultipartFile blob获取的参数是null,具体原因不清楚
* 还有一个主意事项就是入参的参数名要和前面传值的参数名对应上例(blob),否则接收不到参数
*/
JSONObject jsonObject = new JSONObject();
if(!blob.isEmpty()){
if(blob.getSize() >= 5242880){
jsonObject.accumulate("state", "3");
jsonObject.accumulate("msg", "请上传小于5M的文件!");
}else{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsssss");
String id = sdf.format(new Date());
String path = request.getSession().getServletContext().getRealPath("/uploads");
String filename = blob.getOriginalFilename();
String[] endfilename = filename.split("\.");
String finalname = id + "." + endfilename[endfilename.length-1];
File filepath = new File(path, finalname);
if(!filepath.getParentFile().exists()){
filepath.getParentFile().mkdirs();
}
try {
blob.transferTo(new File(path + File.separator + finalname));
jsonObject.accumulate("state", "1");
jsonObject.accumulate("msg", "上传成功!");
jsonObject.accumulate("fileAddress", "/uploads/"+finalname);
} catch (Exception e) {
e.printStackTrace();
}
}
}else{
jsonObject.accumulate("state", "2");
}
return JsonUtils.objectToJson(jsonObject);
}
---------------------