版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuanzhangran/article/details/54929988
如果你想只上传一张图片:http://blog.csdn.net/xuanzhangran/article/details/54928997
上传多张:
可以删除从库里查询出来的图片,也可以删除刚上传到图片,其实不多,为了任务请耐心看完:
效果如下:
1:最开始效果
2:点击上传图片,弹出本地上传,并有删除按钮:
3:点击删除,弹出删除框。
4:点击确认,回到删除之后的状态
前台代码:
<div class="row" style="width:350px;" >
<span class="personattr" style="width:100px;display:inline;">产品轮播图片:</span>
<a href="javascript:void(0);" class="btn_addPic">
<span>上传图片</span>
<input type="file" name="logoFile1" id="logoFile1" onchange="setImg1(this);" style="display:inline;" class="selectedLogoImgId">
<span id="imgss">
<div class="cp-img" style="top:50px;heigh:20px;" id="logoImgDiv5">
<ul id="bannerImg">
<li style="display:none;" id="a0">
<c:forEach items="${imgs}" var="img" varStatus="st">
<li id="a${img.id }">
<input type="hidden" value="${img.id }" name="imgId" id="imgId${img.id }">
<input type="hidden" value="${img.imgUrl }" name="imgUrl" id="imgUrl${img.id }">
<img src="${img.imgUrl }" original='${img.imgUrl }' width="500" height="400" style="border-bottom-width: 0px; padding-top: 20px;">
<a href="#" onclick="deleteImg(${img.id})">删除</a>
</li>
</c:forEach>
</ul>
</div>
</span>
<span id="hiddenss"></span>
</div>
js代码:
//上传图片js
function setImg1(obj){//用于进行图片上传,返回地址
var f=$(obj).val();
if(f == null || f ==undefined || f == ''){
return false;
}
if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f))
{
alertLayel("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
$(obj).val('');
return false;
}
var data = new FormData();
$.each($(obj)[0].files,function(i,file){
data.append('file', file);
});
$.ajax({
type: "POST",
url: "/business/uploadImg.html",
data: data,
cache: false,
contentType: false, //不可缺
processData: false, //不可缺
dataType:"json",
success: function(suc) {
if(suc.code==0){
var id = $('#bannerImg li:last').attr('id');
id = id.substr(1);
id = parseInt(id) + 1;
var ids=id;
id = 'a'+id;
//拼接删除按钮
var a_hidden="<li id='"+ id +"'><input type='hidden' value='"+suc.message+"' name='imgUrl'>";
var img_html="<img src='"+suc.message+"' width='500' height='500'>";
var a_html="<a href='#' onclick='delespan("+ids+")'>删除</a>";
var li_html="</li>";
$('#bannerImg').append(a_hidden+img_html+a_html+li_html);
}else{
alertLayel("上传失败");
$("#url").val("");
$(obj).val('');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alertLayel("上传失败,请检查网络后重试");
$("#url").val("");
$(obj).val('');
}
});
}
//删除图片js:
//本地上传的图片删除,去掉图片的id即可
function delespan(id){
$('#a'+id).remove();
alert("删除成功");
}
//数据库中的图片删除:不同的业务自己处理
function deleteImg(id){
$.ajax({
url: "/business/deleteBannerImg.html?id="+id,
type: "POST",
dataType:'json',
success:function(obj){
if(obj.code == 1){
alert(obj.message);
$('#a'+id).remove();
}else if(obj.code == 0){
alert("删除失败");
return false;
}
}
});
}
后台代码:
package com.idorabox.manage.web.business;
@Controller
@RequestMapping("/business")
import com.idorabox.manage.web.util.TimeUtil;
import com.idorabox.core.utils.DateUtil;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;
import javax.servlet.ServletContext;
import java.util.Random;
import java.io.File;
import java.util.ArrayList;
public class BusinessAction {
@ResponseBody
@RequestMapping("/uploadImg.html")
public String uploadPicture(
@RequestParam(value="file",required=false)MultipartFile file,
HttpServletRequest request){
File targetFile=null;
String msg="";//返回存储路径
int code=1;
String fileName=file.getOriginalFilename();//获取文件名加后缀
if(fileName!=null&&fileName!=""){
String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";//存储路径
String path = request.getSession().getServletContext().getRealPath("upload/imgs"); //文件存储位置
String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名
//先判断文件是否存在
String fileAdd = DateUtil.format(new Date(),"yyyyMMdd");
File file1 =new File(path+"/"+fileAdd);
//如果文件夹不存在则创建
if(!file1 .exists() && !file1 .isDirectory()){
file1 .mkdir();
}
targetFile = new File(file1, fileName);
// targetFile = new File(path, fileName);
try {
file.transferTo(targetFile);
// msg=returnUrl+fileName;
msg=returnUrl+fileAdd+"/"+fileName;
code=0;
} catch (Exception e) {
e.printStackTrace();
}
}
return JSON.toJSONString(ResponseResult.result(code, msg));
}
//数据库中的图片删除,不同的业务自己处理
@RequestMapping("/deleteBannerImg.html")
@ResponseBody
public String deleteBannerImg(
@RequestParam(value = "flag", required = false) String flag,
@RequestParam(value = "id", required = false) Long id,
Model model){
int code = 0;
String message = null;
Map <String , Object> map = new HashMap<String, Object>();
map.put("id", id);
map.put("invalid", true);
map.put("updateTime", new Date());
int num = suBusinessDetailBannerService.updateByPrimaryKeySelective(map);
if(num > 0){
code = 1;
message = "删除成功";
return JSON.toJSONString(ResponseResult.result(code, message));
}
return JSON.toJSONString(ResponseResult.result(code, message));
}
}
//删除或添加图片成功之后,点击保存:
/**
* 对查出来的详情进行修改保存
* @param admin
* @param detail
* @param loginPhone
* @param openTimestartTime
* @param openTimeendTime
* @param banners
* @param model
* @return
*/
@RequestMapping("/view.html")
public String view(//@ModelAttribute("admin") SysAdmin admin,
@ModelAttribute("detailBanner") SuBusinessDetailBanner detailBanner,
@ModelAttribute(value = "detail") SuBusinessDetail detail,
@RequestParam(value = "flag") Integer flag,
@RequestParam(value = "openTimestartTime", required = true) String openTimestartTime,
@RequestParam(value = "openTimeendTime", required = true) String openTimeendTime,
@RequestParam(value = "id", required = false) Long id,
@RequestParam(value = "businessId", required = false) Long businessId,
@RequestParam(value = "imgId", required = false) String imgId,
@RequestParam(value = "imgUrl", required = false) String imgUrl,//店铺详情图片
Model model){
if (StringUtils.isNotBlank(imgId)) {
String[] id1=imgId.split(",");
String[] img=imgUrl.split(",");
int length=img.length-id1.length;
if (length!=0) {
for (int i = 0; i < length; i++) {
SuBusinessDetailBanner banner=new SuBusinessDetailBanner();
banner.setBusinessDetailId(id);
banner.setImgUrl(img[id1.length+i]);
banner.setCreateDateTime(new Date());
banner.setUpdateTime(new Date());
banner.setStatus((byte)1);
banner.setInvalid(false);
int num3=suBusinessDetailBannerService.insert(banner);
System.out.println("num3="+num3);
if(num3>0){
count+=1;
}
}
}
}else {//之前删除的图片
String[] img=imgUrl.split(",");
for (int i = 0; i < img.length; i++) {
SuBusinessDetailBanner banner=new SuBusinessDetailBanner();
banner.setBusinessDetailId(id);
banner.setImgUrl(img[i]);
banner.setCreateDateTime(new Date());
banner.setUpdateTime(new Date());
banner.setStatus((byte)1);
banner.setInvalid(false);
int num3=suBusinessDetailBannerService.insert(banner);
if(num3>0){
count+=1;
}
}
}
if (num>0) {//说明至少有一条数据成功
flag=1;
}else {
flag=2;
}
return "redirect:/business/toView.html?flag="+flag+"&businessId="+businessId;
}