图片的上传
Posted lxnlxn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片的上传相关的知识,希望对你有一定的参考价值。
效果图:
jsp: <script src="../..//platform/js/layer/layer.js"></script> <script src="../../platform/js/ajax/ajaxfileupload.js"></script> <script type="text/javascript"> $(function() { //上传图片 $("#cmsArticleImageFile").change(function() { var cmsArticleImageFile = $("#cmsArticleImageFile").val(); if (cmsArticleImageFile == null || cmsArticleImageFile == "") { layer.tips(‘请选择图片!‘, ‘#mybutton‘, {tips : 3}); } else { $.ajaxFileUpload({ type : ‘POST‘, url : ‘imageUpload.do‘, //用于文件上传的服务器端请求地址 secureuri : false, //是否需要安全协议,一般设置为false fileElementId : ‘cmsArticleImageFile‘, //文件上传域的ID data : { "folderType" : ‘yaoWen‘ }, dataType : ‘json‘, //返回值类型 一般设置为json success : function(result, status) {//服务器成功响应处理函数 if (result.code == "ok") { $(‘#cmsArticleImageFileSrc‘).prop(‘src‘,result.data.filePath); $(‘#articleImage‘).val(result.data.filePath); } else { layer.alert(result.msg); } } }); } }); }); </script> <td> <img id="cmsArticleImageFileSrc" style="height: 320px; width: 440px;" class="img-rounded" data-action="zoom" <c:if test="${!empty cmsArticle.articleImage}"> src="${cmsArticle.articleImage}" </c:if> <c:if test="${empty cmsArticle.articleImage}"> src="${pageContext.request.contextPath}/cms/image/imageNo.jpg" </c:if>> <input id="cmsArticleImageFile" name="cmsArticleImageFile" type="file" style="display:none;" accept="image/png, image/jpeg, image/gif, image/jpg" /> <input id="articleImage" type="text" name="articleImage" value="${cmsArticle.articleImage}" style="display:none;"/> <input id="mybutton" type="button" class="btn btn-info" onclick="$(‘input[id=cmsArticleImageFile]‘).click();" value="浏览并上传"/> </td> controller层: /** * @category 封面图片上传 * @param request * @param response */ @RequestMapping(value = "/.../..../imageUpload", method = RequestMethod.POST) public void cmsImageUpload(HttpServletRequest request, HttpServletResponse response) { //文件类别 String folderType = request.getParameter("folderType"); try { //上传图片 ClientResponse resp = uploadController.uploadAll(request, folderType); // resp.writeTo(response); } catch (Exception e) { e.printStackTrace(); } } //调用方法: public ClientResponse uploadAll(HttpServletRequest request, //客户端请求 String folderType//文件类别 ) throws Exception { String basePath = "upload/" + folderType + "/"; // 相对路径 String filePath = request.getContextPath() + "/" + basePath; // 绝对路径 String savePath = request.getServletContext().getRealPath("/") + basePath; long startTime = System.currentTimeMillis(); // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); if (!multipartResolver.isMultipart(request)) { return ClientResponse.createErrorResult("未找到文件", null); } ClientResponse resp = ClientResponse.createOkResult("ok"); // 检查form中是否有enctype="multipart/form-data" if (multipartResolver.isMultipart(request)) { // 将request变成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // 获取multiRequest 中所有的文件名 Iterator<?> iter = multiRequest.getFileNames(); while (iter.hasNext()) { // 一次遍历所有文件 MultipartFile multipartFile = multiRequest.getFile(iter.next().toString()); if (multipartFile != null) { String originalName = multipartFile.getOriginalFilename(); // 检查扩展名 String fileExt = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase(); if (!Arrays.<String> asList(extMap.get("file").split(",")).contains(fileExt)) { return ClientResponse.createErrorResult("不允许的文件格式,只允许" + extMap.get("image") + "格式。", null); } String newName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "." + fileExt; savePath += newName; filePath += newName; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } // 上传 multipartFile.transferTo(dirFile); //源文件名 resp.addData("originalName", originalName); //上传成后文件路径 resp.addData("filePath", filePath); } } } long endTime = System.currentTimeMillis(); logger.println("上传运行时间:" + String.valueOf(endTime - startTime) + "ms"); return resp; }
以上是关于图片的上传的主要内容,如果未能解决你的问题,请参考以下文章