上传图片功能实现

JSP

<div class="layui-input-block">
    <div class="layui-upload">
        <button type="button" class="layui-btn" id="adimg">点击添加图片</button>						
		<div class="layui-upload-list"></div>
	</div>
</div>
<input name="id" type="hidden" value="${resultMap.id}">
<div class="layui-form picShow" style="margin-left: 150px;">
	<c:choose>
		<c:when test="${ resultMap eq null}">
			<img src="${ctxjt}/common/images/2018.jpg" name="picpath"
				id="imgView"
				style="width: 30%; height: 15%; border: 1px solid #CCC;">
	    </c:when>
		<c:otherwise>
			<img src="${ctxjt}${resultMap.picpath}" name="picpath"
				id="imgView"
				style="width: 30%; height: 15%; border: 1px solid #CCC;">
		</c:otherwise>
	</c:choose>
</div>

JS

//上传图片
var uploadListIns  = upload.render({
    elem: '#adimg', // 绑定元素
    url: ctx + '/upload', // 上传接口
    accept: 'file',//指定允许上传的文件类型,可选值有:images(图片)、file(所有文件)、video(视频)、audio(音频)
	multiple: true,//是否允许多文件上传。设置 true即可开启。不支持ie8/9
	auto: true,//是否选完文件后自动上传。如果设定 false,那么需要设置 bindAction 参数来指向一个其它按钮提交上传
	//bindAction: '#testListAction',//指向一个按钮触发上传,一般配合 auto: false 来使用。
	choose: function(obj){   //选择文件后的回调函数。			 
	    var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列
		//读取本地文件
		obj.preview(function(index, file, result){
		    var tr = $(['<tr id="upload-'+ index +'">',
			    '<td class="filename">'+ file.name +'</td>',
//			    '<td class="filesize">'+ (file.size/1014).toFixed(1) +'kb</td>',
			    '<td>等待上传</td>',
			    '<td>',
			        '<button class="layui-btn layui-btn-mini demo-reload layui-hide">重传</button>',
				     '<a class="demo-delete"><span style="color: #0000FF;">删除</span></a>',
	    		'</td>',
		    	'<td style="display:none">',
			    '</td>',
			'</tr>'].join(''));
            // 单个重传
			tr.find('.demo-reload').on('click', function(){
			    obj.upload(index, file);
			});
		    // 删除
			tr.find('.demo-delete').on('click', function(){
			    delete files[index]; // 删除对应的文件
				tr.remove();
				uploadListIns.config.elem.next()[0].value = ''; // 清空 input file值,以免删除后出现同名文件不可选
			});
        });
	},
    done: function(res, index, upload){
        if(res.code == 0){ // 上传成功
	        var url = ctxjt + res.data.src;
	    	var downPath = ctxa+'/upload/download?filePath='+encodeURIComponent(encodeURIComponent(url));
	            $("#imgView").attr("src",downPath);
        }
	    this.error(index, upload);
    }
});

Controller

String newFileName="";
String fileFullname="";

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Map<String ,Object> uploadFile(HttpServletRequest request,HttpServletResponse response) throws IOException {
    Map<String, Object> result = new HashMap<String, Object>();
	Map<String, Object> resultSrc = new HashMap<String, Object>();
	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	PrintWriter out = response.getWriter();
	String projectName = request.getContextPath();
	String outStr = "";
	// 文件保存目录路径
	String savePath = request.getSession().getServletContext()
        .getRealPath("/common/images/uploadFiles/photo/");
	response.setContentType("text/html; charset=UTF-8");
	/*
        // 检查目录
		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			// 如果不存在,创建文件夹
			if (!uploadDir.exists()) {
				uploadDir.mkdirs();
			}
		}
		String dirName = request.getParameter("dir");
		if (dirName == null) {
			dirName = "image";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		String ymd = sdf.format(new Date());
		savePath += "/" + ymd + "/";
    */
	File dirFile = new File(savePath);
	if (!dirFile.exists()) {
		dirFile.mkdirs();
	}
	// 此处是直接采用Spring的上传
	for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
		MultipartFile mf = entity.getValue();
		fileFullname = mf.getOriginalFilename();
		fileFullname = fileFullname.replace('&', 'a');
		fileFullname = fileFullname.replace(',', 'b');
		fileFullname = fileFullname.replace(',', 'c');
		// 扩展名
		String fileExt = fileFullname.substring(fileFullname.lastIndexOf(".") + 1).toLowerCase();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		newFileName = df.format(new Date()) + "_"+ new Random().nextInt(1000) + "." + fileExt;
		File uploadFile = new File(savePath + "/"+newFileName);
		try {
			FileCopyUtils.copy(mf.getBytes(), uploadFile);
			outStr += projectName + "/common/images/uploadFiles/photo/"+newFileName;		
		} catch (IOException e) {
			result.put("code", 200);
			result.put("msg", "上传失败");
			e.printStackTrace();
		}
	}
	result.put("code", 0);
	result.put("msg", "上传成功");
	resultSrc. put("src", outStr);
	result.put("data", resultSrc);
	return result;
	// 上传结束
}

<另>controller中注意更改保存/saveline:

line.setPicpath("/common/images/uploadFiles/photo/"+newFileName);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过监听粘贴事件,获取剪贴板中的图片,并将其上传到服务器。 以下是一个简单的实现示例: HTML: ```html <div contenteditable="true" id="editor"></div> ``` JavaScript: ```javascript const editor = document.getElementById('editor'); editor.addEventListener('paste', function(e) { const items = (e.clipboardData || e.originalEvent.clipboardData).items; for (let i = 0; i < items.length; i++) { if (items[i].type.indexOf('image') !== -1) { const file = items[i].getAsFile(); uploadImage(file); } } }); function uploadImage(file) { const formData = new FormData(); formData.append('image', file); // 发送 ajax 请求上传图片 const xhr = new XMLHttpRequest(); xhr.open('POST', '/upload-image'); xhr.send(formData); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { const imageUrl = xhr.responseText; insertImage(imageUrl); } } } function insertImage(imageUrl) { const img = document.createElement('img'); img.src = imageUrl; editor.appendChild(img); } ``` 在上面的代码中,我们监听了 `paste` 事件,获取剪贴板中的所有项目。如果项目的类型是图片,就将其转换为 `File` 对象,并调用 `uploadImage` 函数上传图片。 在 `uploadImage` 函数中,我们创建了一个 `FormData` 对象,将图片文件添加到其中,并使用 AJAX 发送请求将数据上传到服务器。 在上传成功后,我们调用 `insertImage` 函数将图片插入到编辑器中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值