图片上传--Upload
图片上传--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的更多相关文章
- PHP上传类 图片上传 upload class实现image crop resize 缩略图
manage uploaded files, and manipulate images in many ways through an HTML form, a Flash uploader, XM ...
- JSP+Servlet中使用jspsmartupload.jar进行图片上传下载
JSP+Servlet中使用cos.jar进行图片上传 upload.jsp <form action="FileServlet" method="post&quo ...
- .Net之Layui多图片上传
前言: 多图上传在一些特殊的需求中我们经常会遇到,其实多图上传的原理大家都有各自的见解.对于Layui多图上传和我之前所说的通过js获取文本框中的文件数组遍历提交的原理一样,只不过是Layui中的up ...
- thinkphp5+layui多图片上传
准备资料 下载layui <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...
- kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸
kindeditor多图片上传找不到action原来是private File upload成员变量惹得祸
- ASP.NET 图片上传工具类 upload image简单好用功能齐全
使用方法: UploadImage ui = new UploadImage(); /***可选参数***/ ui.SetWordWater = "哈哈";//文字水印 // ui ...
- Asp.Net Mvc 使用WebUploader 多图片上传
来博客园有一个月了,哈哈.在这里学到了很多东西.今天也来试着分享一下学到的东西.希望能和大家做朋友共同进步. 最近由于项目需要上传多张图片,对于我这只菜鸟来说,以前上传图片都是直接拖得控件啊,而且还是 ...
- 06.LoT.UI 前后台通用框架分解系列之——浮夸的图片上传
LOT.UI分解系列汇总:http://www.cnblogs.com/dunitian/p/4822808.html#lotui LoT.UI开源地址如下:https://github.com/du ...
- TinyMCE的使用(包括汉化及本地图片上传功能)
TinyMCE我就不多介绍了,这是下载地址:https://www.tinymce.com/download/ 下载下来是英文版,要汉化也很简单.首先去网上随便下载个汉化包,然后把汉化包解压后的lan ...
随机推荐
- (四)github之Git的初始设置
设置姓名与邮箱地址 这里的姓名和邮箱地址会用在git的提交日志之中,在github上公开git仓库时会随着提交日志一起公开. 有两种方式, 第一种,在git bash下设置 第二种, 通过直接编辑.g ...
- P2512 [HAOI2008]糖果传递&&P3156 [CQOI2011]分金币&&P4016 负载平衡问题
P2512 [HAOI2008]糖果传递 第一步,当然是把数据减去平均数,然后我们可以得出一串正负不等的数列 我们用sum数组存该数列的前缀和.注意sum[ n ]=0 假设为链,那么可以得出答案为a ...
- P3008 [USACO11JAN]道路和飞机Roads and Planes
P3008 [USACO11JAN]道路和飞机Roads and Planes Dijkstra+Tarjan 因为题目有特殊限制所以不用担心负权的问题 但是朴素的Dijkstra就算用堆优化,也显然 ...
- MIME协议(详解范例)
转载一:http://blog.csdn.net/bripengandre/article/details/2192982 转载二:http://blog.csdn.net/flfna/article ...
- BZOJ 1063 道路设计(树形DP)
题目链接:http://61.187.179.132/JudgeOnline/problem.php?id=1063 题意:给出一个无环图( 也就是树,但是也有可能是森林),代表一个国家的城市.1是首 ...
- cogs 2221. [SDOI2016 Round1] 数字配对
★★ 输入文件:pair.in 输出文件:pair.out 简单对比 时间限制:1 s 内存限制:128 MB [题目描述] 有 n 种数字,第 i 种数字是 ai.有 bi 个,权值是 ci. 若两 ...
- python装饰器,其实就是对闭包的使用。
装饰器 理解装饰器要先理解闭包(在闭包中引用函数,可参考上一篇通过例子来理解闭包). 在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator). 装饰器的实质就是对闭包的使用,原函数被 ...
- Go第十一篇之编译与工具
Go 语言的工具链非常丰富,从获取源码.编译.文档.测试.性能分析,到源码格式化.源码提示.重构工具等应有尽有. 在 Go 语言中可以使用测试框架编写单元测试,使用统一的命令行即可测试及输出测试报告的 ...
- C简介与环境配置
C 语言是一种通用的高级语言,最初是由丹尼斯·里奇在贝尔实验室为开发 UNIX 操作系统而设计的.C 语言最开始是于 1972 年在 DEC PDP-11 计算机上被首次实现. 在 1978 年,布莱 ...
- Several Service Control Manager Issues (Event ID's 7000, 7009, 7011)
https://answers.microsoft.com/en-us/windows/forum/windows_7-performance/several-service-control-mana ...