bootstrap-input 上传图片







1、publish.JSP


<!-- Bootstrap Core CSS -->
    <link href="<spring:url value="/resources/SBAdmin2/bower_components/bootstrap/dist/css/bootstrap.min.css"/>" rel="stylesheet">
   
<link href="<spring:url value="/resources/bootstrap-datepicker/css/bootstrap-datepicker3.min.css"/>" rel="stylesheet" type="text/css">
<!-- 图片附件上传 -->
<link href="<spring:url value="/resources/bootstrap-fileinput/css/fileinput.css"/>" media="all" rel="stylesheet" type="text/css" />


<div id="imgGroup" class="form-group" style="margin-top: 10px;margin-left: 10px;">
<label class="col-sm-2 control-label">图片上传:</label>
<div class="col-md-8">
<input id="file1" name="file" type="file" accept="image/jpeg,image/png,image/gif" multiple>
</div>
</div>

<div class="form-group" style="margin-top: 10px;margin-left: 10px;">
  <label class="col-sm-2 control-label" style="font-weight:normal">注明:</label>
  <div style="margin-top:5px;">
<font class="required">(每次只能上传一张图片,最多上传三张。选择图片之后请点击上传。)</font></div>
 </div>

<script
src="<spring:url value="/resources/SBAdmin2/bower_components/jquery/dist/jquery.min.js"/>"></script>
<script
src="<spring:url value="/resources/SBAdmin2/bower_components/bootstrap/dist/js/bootstrap.min.js"/>"></script>

 <script src="<spring:url value="/resources/bootstrap-datepicker/js/bootstrap-datepicker.min.js"/>"></script>
    <script src="<spring:url value="/resources/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"/>"></script>
<!-- 图片上传 -->
<script src="<spring:url value="/resources/bootstrap-fileinput/js/fileinput.js"/>" type="text/javascript"></script>
<script src="<spring:url value="/resources/bootstrap-fileinput/js/fileinput_locale_zh.js"/>" type="text/javascript"></script>
<script src="<spring:url value="/resources/js/back/land/publish.js"/>"></script>


2、publish.JS
//上传图片初始化###红色链接不能变名字,可以用类似back/car/upload替换之,   规范点;(推翻之前的,有待继续考察)
$('#file1').fileinput({
        language: 'zh',
        uploadUrl: ' upload',       
        previewFileType:'any',
        maxFileSize:5120,
        maxFileCount:1,
        minImageWidth:580,
        minImageHeight:250,
        allowedFileExtensions : ['jpg', 'png','gif'],
        fileCountLimit:3
    });
$('#file1').on('fileuploaded', function(event, data, previewId, index) {
   var response = data.response;
   $("#imgGroup").prepend("<input type=\"hidden\" name=\"fileName\" value=\""+response.fileName+"\" >");
   $("#"+previewId).attr("fileName",response.fileName);
});
$('#file1').on('filesuccessremove', function(event, id) {
var prefileName=$("#"+id).attr("fileName");
$('input:hidden[value="'+prefileName+'"]').remove();
});
$('#file1').on('filecleared', function(event) {
clearImgInfo();
});
$('#file1').on('changediy', function(event,self) {
// alert(self.fileCountLimit);
var fileCountLimit=self.fileCountLimit;
var count=0;
$("input[name=fileName]").each(function(){
    count=count+1;
   });
if(count>=fileCountLimit){
self.isDenied=true;
}
});
});


3、BackController.java
/*
* 发布土地信息提交审核
*/
@RequestMapping(value="/publishSave",method=RequestMethod.POST)
public String publishSave(Model model,@Valid LandInfoEntity landInfo,BindingResult result,
HttpServletRequest request,HttpServletResponse response,
@RequestParam(value="landtype",required=false) String landtype,
@RequestParam(value="landstatus",required=false) String landstatus,
@RequestParam(value="fileName",required=false) String fileName
){
try{
publishService.lastModified(request, landInfo);
publishService.setLandTypeAndStatus(landInfo,landtype, landstatus);
landInfo.setInfoStatus(1);
landInfo.setSfdel(2);
String detailss=StringEscapeUtils.escapeHtml4(landInfo.getDetail());
landInfo.setDetail(detailss.replaceAll("\r\n", "<br/>"));
publishService.getPublishDao().save(landInfo);
publishService.saveFile(landInfo, fileName);
publishService.setDefaultImg(landInfo);
}catch(Exception e){
e.printStackTrace();
return "/back/land/error";
}
return "/back/land/success";
}
/*
* 图片上传
*/
@ResponseBody
@RequestMapping(value="/upload",method=RequestMethod.POST)
public Map<String,String> upload(@RequestParam("file")MultipartFile[] files){
Map<String,String> map=null;
try {
map=publishService.uploadImg(files);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}






4、PublishService.java
package cn.com.tudi.service;

import java.util.List;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.com.tudi.dao.PublishDao;
import cn.com.tudi.dao.UserDao;
import cn.com.tudi.entity.LandAttachmentEntity;
import cn.com.tudi.entity.LandInfoEntity;
import cn.com.tudi.entity.LandStatusEntity;
import cn.com.tudi.entity.LandTypeEntity;
import cn.com.tudi.entity.UserEntity;


@Service
public class PublishService {
public static final String THUMB_SUFFIX="_thumb";
@Value("${land.relativePath}")
private String relativePath;//原图访问相对路径
@Value("${land.relativePathThumb}")
private String relativePathThumb;//缩略图访问相对路径
@Value("${land.savePath}")
private String savePath;//原图正式保存路径
@Value("${land.thumbSavePath}")
private String thumbSavePath;//缩略图正式保存路径
@Value("${land.tmpfile.savePath}")
private String tmpSavePath;//原图临时保存路径
@Value("${land.maxWidth}")
private Integer maxWidth;//图片裁剪的最大宽度
@Value("${land.maxHeight}")
private Integer maxHeight;//图片裁剪的最大高度
@Autowired
private UserDao userDao;
@Autowired
private PublishDao publishDao;
@Autowired
private UserService userService;
@Autowired
private LandTypeService landTypeService;
@Autowired
private LandStatusService landStatusService;
@Autowired
private LandAttachmentService landAttachmentService;
@Autowired
private LandInfoService landInfoService;
//记录创建人创建时间
public LandInfoEntity lastModified(HttpServletRequest request,LandInfoEntity landInfo){
String creator = userService.getCurrentUser().getUsername();
landInfo.setLastModifiedDate(new Date());
landInfo.setLastModifier(creator);
//判断新增和编辑
if(landInfo.getId() == null){
landInfo.setCreateDate(new Date());
landInfo.setCreator(userService.getCurrentUser().getUsername());
UserEntity user = new UserEntity();
user.setId(userService.getCurrentUser().getId());
landInfo.setUser(user);
}
return landInfo;
}
//发布、编辑土地信息,保存图片实体
public void saveFile(LandInfoEntity landInfo,String fileName) throws IOException{
if(fileName != null && !fileName.equals("")){
String[] fileArray=fileName.split(",");
for(String fName:fileArray){
//System.out.println(fName);
String todayDir="/"+DateTime.now().toString("yyyyMMdd");
//将临时文件复制到正式文件目录里
File tmpImg=new File(tmpSavePath,fName);
File img=new File(savePath+todayDir,fName);
FileUtils.copyFile(tmpImg, img);
String filename=fName.substring(0, fName.lastIndexOf("."));
String extension=fName.substring(fName.lastIndexOf("."));
String fileNameThumb=filename+THUMB_SUFFIX;
File thumbDir=new File(thumbSavePath+todayDir);
if(!thumbDir.exists()){
thumbDir.mkdirs();
}
File thumbImg=new File(thumbDir,fileNameThumb+extension);
Thumbnails.of(img).size(maxWidth, maxHeight).toFile(thumbImg);
LandAttachmentEntity atts = this.landAttachmentService.getLandAttachmentDao().findByFileName(filename);
if(atts == null){
LandAttachmentEntity attach = new LandAttachmentEntity();
attach.setAttachName(filename);  //附件名称
attach.setFileName(filename);  //原图文件名称
attach.setFileNameThumb(fileNameThumb);     //缩略图文件名
attach.setExtension(extension);  //缩略图扩展名
attach.setAttachPath(relativePath+todayDir);  //原始图访问相对路径
attach.setAttachPathThumb(relativePathThumb+todayDir); //缩略图访问相对路径
attach.setAttachType(1);
LandInfoEntity lands = new LandInfoEntity();
lands.setId(landInfo.getId());
attach.setLandinfo(lands);
this.landAttachmentService.getLandAttachmentDao().save(attach);
}
}
}
}
//设置缩略图相对路径保存到土地信息实体
public void setDefaultImg(LandInfoEntity landInfo){
List<LandAttachmentEntity> attachs = this.landAttachmentService.getLandAttachmentDao().findByLandinfoId(landInfo.getId());
if(attachs != null && attachs.size()>0){
LandAttachmentEntity attach = attachs.get(0);
String imgPath = attach.getAttachPathThumb()+"/"+attach.getFileNameThumb()+attach.getExtension();
landInfo.setDefaultImg(imgPath);
this.landInfoService.getLandInfoDao().save(landInfo);
}else{
landInfo.setDefaultImg(null);
this.landInfoService.getLandInfoDao().save(landInfo);
}
}
public LandInfoEntity setLandTypeAndStatus(LandInfoEntity landInfo,String landtype,String landstatus){
LandTypeEntity type = landTypeService.getLandTypeDao().findByNameAndLevel(landtype, 1);
LandStatusEntity status = landStatusService.getLandStatusDao().findByNameAndLevel(landstatus, 2);
if(type != null){
LandTypeEntity landTypes = new LandTypeEntity();
landTypes.setId(type.getId());
landInfo.setLandtype(landTypes);
}
if(status != null){
LandStatusEntity landStatuss = new LandStatusEntity();
landStatuss.setId(status.getId());
landInfo.setLandstatus(landStatuss);
}
return landInfo;
}
/**
* 发布土地信息多图片上传图片
* @param files
* @return
* @throws IllegalStateException
* @throws IOException
*/
public Map<String,String> uploadImg(MultipartFile[] files) throws IllegalStateException, IOException{
Map<String,String> map=new HashMap<String,String>();
if(files != null && files.length >0){
File saveDir = new File(tmpSavePath);
if (!saveDir.exists()) {
saveDir.mkdirs();
}
for(int i=0;i<files.length;i++){
MultipartFile file = files[i];
String imgOriName=file.getOriginalFilename();
String ext=imgOriName.substring(imgOriName.lastIndexOf("."));
Date now = new Date();
String newImgFilename=DateTime.now().toString("yyyyMMddHHmmss")+now.getTime()+ext;
File img=new File(tmpSavePath,newImgFilename);
file.transferTo(img);
map.put("fileName", newImgFilename);
}
}
return map;
}
public PublishDao getPublishDao() {
return publishDao;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值