图片上传--Upload

  图片上传基于spring框架写的代码:

    1.首先:我们要再springmvc中添加试图解析器:

     <!-- 图片解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880"></property>
<property name="defaultEncoding" value="utf-8"></property>
</bean>

    2.然后封装一个图片返回类

 package com.taotao.manage.bean;

 public class PicUploadResult {
private Integer error; private String url; private String width; private String height; public Integer getError() {
return error;
} public void setError(Integer error) {
this.error = error;
} public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} public String getWidth() {
return width;
} public void setWidth(String width) {
this.width = width;
} public String getHeight() {
return height;
} public void setHeight(String height) {
this.height = height;
} }

  3.写一个userController

 package com.taotao.manage.controller;

 import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date; import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.manage.bean.PicUploadResult;
import com.taotao.service.impl.UpLoadServiceImpl; /**
* 图片上传
*/
@Controller
@RequestMapping("/pic")
public class PicUploadController { private static final Logger LOGGER = LoggerFactory.getLogger(PicUploadController.class); @Autowired
private UpLoadServiceImpl loadService;
private static final ObjectMapper mapper = new ObjectMapper(); // 允许上传的格式
private static final String[] IMAGE_TYPE = new String[] { ".bmp", ".jpg", ".jpeg", ".gif", ".png" }; @RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletResponse response)
throws Exception { // 校验图片格式
boolean isLegal = false;
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
isLegal = true;
break;
}
} // 封装Result对象,并且将文件的byte数组放置到result对象中
PicUploadResult fileUploadResult = new PicUploadResult(); // 状态 圖片格式正确时为:0,错误时为:1
fileUploadResult.setError(isLegal ? 0 : 1); // 文件新路径
String filePath = getFilePath(uploadFile.getOriginalFilename()); if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Pic file upload .[{}] to [{}] .", uploadFile.getOriginalFilename(), filePath);
} // 生成图片的绝对引用地址
String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath, loadService.TAOTAO_UPLOAD_RESPOSITORY),
"\\", "/");
// 用来显示图片的路径
fileUploadResult.setUrl(loadService.TAOTAO_IMAGES_URL + picUrl); File newFile = new File(filePath); // 写文件到磁盘
uploadFile.transferTo(newFile); // 校验图片是否合法
isLegal = false;
try {
BufferedImage image = ImageIO.read(newFile);
if (image != null) {
fileUploadResult.setWidth(image.getWidth() + "");
fileUploadResult.setHeight(image.getHeight() + "");
isLegal = true;
}
} catch (IOException e) {
} // 状态
fileUploadResult.setError(isLegal ? 0 : 1); if (!isLegal) {
// 不合法,将磁盘上的文件删除
newFile.delete();
} response.setContentType(MediaType.TEXT_HTML_VALUE);
return mapper.writeValueAsString(fileUploadResult);
} // 获取文件路径
// 接受的参数时上传文件的文件名
private String getFilePath(String sourceFileName) {
// File.separator:/
String baseFolder = loadService.TAOTAO_UPLOAD_RESPOSITORY + File.separator + "images";
Date nowDate = new Date();
// yyyy/MM/dd
String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy") + File.separator
+ new DateTime(nowDate).toString("MM") + File.separator + new DateTime(nowDate).toString("dd");
File file = new File(fileFolder);
if (!file.isDirectory()) {
// 如果目录不存在,则创建目录
file.mkdirs();
}
// 生成新的文件名
String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS") + RandomUtils.nextInt(100, 9999) + "."
+ StringUtils.substringAfterLast(sourceFileName, ".");
return fileFolder + File.separator + fileName;
} }

    4.写页面的js代码

  init : function(data){
// 图片初始化
this.initPicUpload(data); },
// 初始化图片上传组件
initPicUpload : function(data){
$(".picFileUpload").each(function(i,e){
var _ele = $(e);
// 获取当前元素得兄弟元素
_ele.siblings("div.pics").remove();
_ele.after('\
<div class="pics">\
<ul></ul>\
</div>');
// 回显图片
if(data && data.pics){
var imgs = data.pics.split(",");
for(var i in imgs){
if($.trim(imgs[i]).length > 0){
_ele.siblings(".pics").find("ul").append("<li><a href='"+imgs[i]+"' target='_blank'><img src='"+imgs[i]+"' width='80' height='50' /></a></li>");
}
}
}
$(e).click(function(){
var form = $(this).parentsUntil("form").parent("form");
KindEditor.editor(TT.kingEditorParams).loadPlugin('multiimage',function(){
var editor = this;
editor.plugin.multiImageDialog({
clickFn : function(urlList) {
var imgArray = [];
KindEditor.each(urlList, function(i, data) {
alert(data)
alert(JSON.stringify(data));
imgArray.push(data.url);
form.find(".pics ul").append("<li><a href='"+data.url+"' target='_blank'><img src='"+data.url+"' width='80' height='50' /></a></li>");
});
form.find("[name=image]").val(imgArray.join(","));
editor.hideDialog();
}
});
});
});
});
},

  然后效果为:

  

  OK!!!

图片上传--Upload的更多相关文章

  1. PHP上传类 图片上传 upload class实现image crop resize 缩略图

    manage uploaded files, and manipulate images in many ways through an HTML form, a Flash uploader, XM ...

  2. JSP+Servlet中使用jspsmartupload.jar进行图片上传下载

    JSP+Servlet中使用cos.jar进行图片上传 upload.jsp <form action="FileServlet" method="post&quo ...

  3. .Net之Layui多图片上传

    前言: 多图上传在一些特殊的需求中我们经常会遇到,其实多图上传的原理大家都有各自的见解.对于Layui多图上传和我之前所说的通过js获取文本框中的文件数组遍历提交的原理一样,只不过是Layui中的up ...

  4. thinkphp5+layui多图片上传

    准备资料 下载layui <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  5. kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸

    kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸

  6. ASP.NET 图片上传工具类 upload image简单好用功能齐全

    使用方法: UploadImage ui = new UploadImage(); /***可选参数***/ ui.SetWordWater = "哈哈";//文字水印 // ui ...

  7. Asp.Net Mvc 使用WebUploader 多图片上传

    来博客园有一个月了,哈哈.在这里学到了很多东西.今天也来试着分享一下学到的东西.希望能和大家做朋友共同进步. 最近由于项目需要上传多张图片,对于我这只菜鸟来说,以前上传图片都是直接拖得控件啊,而且还是 ...

  8. 06.LoT.UI 前后台通用框架分解系列之——浮夸的图片上传

    LOT.UI分解系列汇总:http://www.cnblogs.com/dunitian/p/4822808.html#lotui LoT.UI开源地址如下:https://github.com/du ...

  9. TinyMCE的使用(包括汉化及本地图片上传功能)

    TinyMCE我就不多介绍了,这是下载地址:https://www.tinymce.com/download/ 下载下来是英文版,要汉化也很简单.首先去网上随便下载个汉化包,然后把汉化包解压后的lan ...

随机推荐

  1. Linux学习笔记之Linux Centos关闭防火墙

    # Centos6.x /etc/init.d/iptables stop chkconfig iptables off sed -i 's/SELINUX=enforcing/SELINUX=dis ...

  2. RSA加解密用途简介及java示例

    在公司当前版本的中间件通信框架中,为了防止非授权第三方和到期客户端的连接,我们通过AES和RSA两种方式的加解密策略进行认证.对于非对称RSA加解密,因为其性能耗费较大,一般仅用于认证连接,不会用于每 ...

  3. 20145335郝昊《网络攻防》Exp4 MS11_050

    20145335郝昊<网络攻防>Exp4 MS11_050 实验内容 初步掌握平台matesploit的使用 了解漏洞MS11_050漏洞:use-after-free漏洞,即对象被释放之 ...

  4. C#调用非托管dll

    以C#开发周立功CAN举例,在官网下载了周立功的demo 一.C++头文件样子 //接口卡类型定义#define VCI_PCI5121 1 //一些结构体定义 typedef struct tagR ...

  5. AD快捷键

    * 在PCB电气层之间切换.在布线的过程中,按此键则换层并自动添加过孔并换层. Q 在公制和英制之间切换 J+C 定位到指定的元件处.在弹出的对话框内输入该元件的编号. G+G 设定栅格吸附尺寸. T ...

  6. linux内核启动参数解析及添加

    1.环境: ubuntu16.04 Linux jello 4.4.0-89-generic #112-Ubuntu SMP Mon Jul 31 19:38:41 UTC 2017 x86_64 x ...

  7. Java命令使用 jmap,jps,jstack,jstat,jhat,jinfo

    Jmap:可以获得运行中的jvm的堆的快照,从而可以离线分析堆,以检查内存泄漏,检查一些严重影响性能的大对象的创建,检查系统中什么对象最多,各种对象所占内存的大小等等 Jmap是一个可以输出所有内存中 ...

  8. 最全的Spring面试题和答案<一>

    1.什么是Spring框架?Spring框架有哪些主要模块? Spring框架是一个为Java应用程序的开发提供了综合.广泛的基础性支持的Java平台.Spring帮助开发者解决了开发中基础性的问题, ...

  9. SpringJDBC源码分析记录

    我们使用JdbcTemplate时,调用的query方法为: public <T> List<T> query(String sql, @Nullable Object[] a ...

  10. [Pytorch]Pytorch中图像的基本操作(TenCrop)

    转自:https://www.jianshu.com/p/73686691cf13 下面是几种常写的方式 第一种方式 normalize = transforms.Normalize([0.485, ...