在看这篇博文之前,你应该先搭好SpringMVC框架,并下载amazeUI包,并参见教程配置好,具体参见百度上的教程,教程很多,这里就不多说啦。
下面是表单的信息,其中,图片上传实现了多张图片的上传,并且可以在线预览。
<form class="am-form am-form-horizontal" method="post" id="edit-form" action="nmgindexintro /save" />">
<input type="hidden" name="branchId" value="${branchId}">
<fieldset>
<legend>内蒙古公司展示legend>
<div class="am-g">
<div class="am-u-sm-8">
<div class="am-form-group am-form-select am-g">
<label for="oc-ds-select-1" class="am-u-sm-2 am-form-label" style="font-size:12px;">文章类型label>
<div class="am-u-sm-4 am-u-end">
<select name="type" id="oc-ds-select-1">
<option value="1">风土人情option>
<option value="2">经济概况option>
<option value="3">行业概况option>
select>
div>
div>
<div class="am-form-group am-g">
<label for="doc-ipt-title-1" class="am-u-sm-2 am-form-label" style="font-size:12px;">标题label>
<div class="am-u-sm-4 am-u-end">
<input type="text" id="doc-ipt-title-1" placeholder="输入标题" name="title" >
div>
div>
<div class="am-form-group am-form-file am-g">
<label for="doc-ipt-file-2" class="am-u-sm-2 am-form-label" style="font-size:12px;">选择图片label>
<div class="am-u-sm-4 am-u-end">
<button type="button" class="am-btn am-btn-default am-btn-sm">
<i class="am-icon-cloud-upload">i> 选择图片button>
div>
<input type="file" id="doc-ipt-file-2" name="titleImage" multiple onchange="javascript:setImagePreviews();" accept=".jpg, .png ,.gif , .jpeg">
div>
<div id="file-list">div>
<div class="am-form-group am-form-file am-g">
<label for="doc-ipt-file-3" class="am-u-sm-2 am-form-label" style="font-size:12px;">选择.MP4文件label>
<div class="am-u-sm-4 am-u-end">
<button type="button" class="am-btn am-btn-default am-btn-sm">
<i class="am-icon-cloud-upload">i> 选择.MP4文件button>
div>
<input type="file" id="doc-ipt-file-3" name="video" accept=".mp4">
div>
<div id="file-list2">div>
div>
<div class="am-u-sm-4" id="preview" style=" width:300px;height:220px;overflow:auto;">预览图片div>
div>
<div class="am-form-group am-form-select am-g">
<fieldset>
<legend>公司展示legend>
<input type="hidden" name="id" value="${info.id}">
<script id="container" name="content" type="text/plain" >
script>
fieldset>
div>
<div class="am-g">
<p class="am-u-sm-1 am-u-sm-centered"><button type="submit" class="am-btn am-btn-default ">提交button>p>
div>
fieldset>
form>
<script>
$('#doc-ipt-file-2').on('change', function() {
var fileNames = '';
$.each(this.files, function() {
fileNames += '' + this.name + ' ';
});
$('#file-list').html(fileNames);
});
$('#doc-ipt-file-3').on('change', function() {
var fileNames = '';
$.each(this.files, function() {
fileNames += '' + this.name + ' ';
});
$('#file-list2').html(fileNames);
});
//图片预览功能
//下面用于多图片上传预览功能
function setImagePreviews(avalue) {
//获取选择图片的对象
var docObj = document.getElementById("doc-ipt-file-2");
//后期显示图片区域的对象
var dd = document.getElementById("preview");
dd.innerHTML = "";
//得到所有的图片文件
var fileList = docObj.files;
//循环遍历
for (var i = 0; i < fileList.length; i++) {
//动态添加html元素
dd.innerHTML += " ";
//获取图片imgi的对象
var imgObjPreview = document.getElementById("img"+i);
if (docObj.files && docObj.files[i]) {
//火狐下,直接设img属性
imgObjPreview.style.display = 'block';
imgObjPreview.style.width = '200px';
imgObjPreview.style.height = '180px';
//imgObjPreview.src = docObj.files[0].getAsDataURL();
//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要以下方式
imgObjPreview.src = window.URL.createObjectURL(docObj.files[i]); //获取上传图片文件的物理路径
}
else {
//IE下,使用滤镜
docObj.select();
var imgSrc = document.selection.createRange().text;
//alert(imgSrc)
var localImagId = document.getElementById("img" + i);
//必须设置初始大小
localImagId.style.width = "200px";
localImagId.style.height = "180px";
//图片异常的捕捉,防止用户修改后缀来伪造图片
try {
localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}
catch (e) {
alert("您上传的图片格式不正确,请重新选择!");
return false;
}
imgObjPreview.style.display = 'none';
document.selection.empty();
}
}
return true;
}
接下来是后台处理程序
Controller主要是保存图片,并且记下图片的路径并创建唯一名称,传至后台入数据库。
@RequestMapping(value={"/save"}, method=RequestMethod.POST)
@ResponseBody
public String save(@RequestParam("titleImage") MultipartFile[] titleImage,@RequestParam("video") MultipartFile video,HttpServletRequest servletRequest) throws IOException {
List listPicture=new LinkedList();
for(MultipartFile picture : titleImage){
if(picture.isEmpty()){
System.out.println("图片未上传");
}else{
String savePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + request.getContextPath()
+ "/static/js/u_editor/jsp/upload/";
String realPath = request.getSession().getServletContext().getRealPath("/static/js/u_editor/jsp/upload");
System.out.println(savePath);
System.out.println(realPath);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String str = sdf.format(date)+picture.getOriginalFilename();
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
FileUtils.copyInputStreamToFile(picture.getInputStream(), new File(realPath, str));
listPicture.add(savePath+str);
}
}
String Video=null;
if(video.isEmpty()){
System.out.println("视频未上传");
}else{
String savePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + request.getContextPath()
+ "/static/js/u_editor/jsp/upload/";
String realPath = request.getSession().getServletContext().getRealPath("/static/js/u_editor/jsp/upload");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String str = sdf.format(date);
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
FileUtils.copyInputStreamToFile(video.getInputStream(), new File(realPath, str+video.getOriginalFilename()));
Video = savePath+str+video.getOriginalFilename();
System.out.println(Video);
}
NmgIndexIntroUpdateRequest request =new NmgIndexIntroUpdateRequest();
request.setContent(servletRequest.getParameter("content"));
request.setTitle(servletRequest.getParameter("title"));
request.setTitleImage(listPicture);
request.setVideo(Video);
request.setType(servletRequest.getParameter("type"));
request.setBranchId(servletRequest.getParameter("branchId"));
NmgIndexIntroAccesser accesser = this.accesserFactory.createAccesser(NmgIndexIntroAccesser.class,CurrentUser.getAccessToken());
JSONObject result = new JSONObject();
try{
Response response = accesser.save(request);
switch (Status.fromStatusCode(response.getStatus())) {
case FOUND:
result.put("success", false);
result.put("msg", "文章已存在");
break;
case OK:
String uuid = response.readEntity(String.class);
result.put("success", true);
result.put("uuid", uuid);
result.put("msg", "创建成功");
break;
default:
result.put("success", false);
result.put("msg", "操作失败,请重试。");
break;
}
return result.toString();
} finally {
accesser.close();
}
}
Accesser,连接前台与后台的桥梁,通过调用相应的接口,连接后台,并将实体和图片路径入库。
@Override
public Response save(NmgIndexIntroUpdateRequest request) {
Assert.notNull(this.access_token, "access token required");
String uri = ResteasyWebResourceMap.get("NmgIndexIntroInterface.save");
AccessParameter parameters = new AccessParameter();
parameters.appendQueryParam("access_token", access_token);
ResteasyWebTarget target = this.buildJsonTarget(uri, parameters);
Response response = target.request().post(Entity.json(request));
return response;
}
Interface接口类,连接后台资源。
package com.kinth.admin.server.rest.api.interfaces;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import com.kinth.base.rest.api.entity.NmgIndexIntroListRequest;
import com.kinth.base.rest.api.entity.NmgIndexIntroSearch;
import com.kinth.security.persistent.entity.NmgIndexIntroUpdateRequest;
@Path("admin/nmgindexintro")
public interface NmgIndexIntroInterface {
/**
* 分页查询列表
* @param request
* @return
*/
@POST
@Path("search")
Response search(NmgIndexIntroSearch request);
/**
* 更新
* @param
* @return
*/
@PUT
@Path("update")
Response update(NmgIndexIntroUpdateRequest request);
/**
* 详情
* @param
* @return
*/
@POST
@Path("edit")
Response get(Integer id);
@POST
@Path("list")
Response list(NmgIndexIntroListRequest request);
@POST
@Path("save")
Response save(NmgIndexIntroUpdateRequest request);
}
Resourse连接底层DAO层,将实体和图片,视频路径入库。
@Override
public Response save(NmgIndexIntroUpdateRequest request) {
NmgIndexIntro nmg= NmgIndexIntroDao.findBybranchIdAndType(request.getBranchId(), request.getType());
if(nmg != null) {
return Response.status(Status.FOUND)
.entity(new ErrorResponse("文章已存在", "文章已存在"))
.build();
}
NmgIndexIntro nii=new NmgIndexIntro();
nii.setBranchId(request.getBranchId());
nii.setContent(request.getContent());
nii.setCreateTime(new Date());
nii.setStatus("1");
nii.setTitle(request.getTitle());
if(request.getTitleImage()!=null){
String titleImage="";
for(String s:request.getTitleImage()){
titleImage+=s;
titleImage+=",";
}
nii.setTitleImage(titleImage);
}
nii.setType(request.getType());
if(request.getVideo()!=""){
nii.setVideo(request.getVideo());
}
nii.setShortContent(request.getTitle()+request.getTitleImage());
this.NmgIndexIntroDao.saveAndFlush(nii);
return Response.ok().build();
}
DAO层
package com.kinth.security.persistent.dao;
import com.kinth.base.persistent.BaseDAO;
import com.kinth.security.persistent.entity.NmgIndexIntro;
public interface NmgIndexIntroDAO extends BaseDAO{
NmgIndexIntro findBybranchId(String branchId);
NmgIndexIntro findById(Integer id);
NmgIndexIntro findBybranchIdAndId(String branchId,Integer id);
NmgIndexIntro findBybranchIdAndType(String brandId,String Type);
}
实体entity
package com.kinth.security.persistent.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
/**
* The persistent class for the nmg_index_intro database table.
*
*/
@Entity
@Table(name="nmg_index_intro")
@NamedQuery(name="NmgIndexIntro.findAll", query="SELECT n FROM NmgIndexIntro n")
public class NmgIndexIntro implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String branchId;
private String content;
private Date createTime;
private String shortContent;
private String status;
private String title;
private String titleImage;
private String type;
private String video;
public NmgIndexIntro() {
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="branch_id")
public String getBranchId() {
return this.branchId;
}
public void setBranchId(String branchId) {
this.branchId = branchId;
}
@Lob
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="create_time")
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Lob
@Column(name="short_content")
public String getShortContent() {
return this.shortContent;
}
public void setShortContent(String shortContent) {
this.shortContent = shortContent;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name="title_image")
public String getTitleImage() {
return this.titleImage;
}
public void setTitleImage(String titleImage) {
this.titleImage = titleImage;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
@Column(name="video")
public String getVideo() {
return this.video;
}
public void setVideo(String video) {
this.video = video;
}
}