模态框图片上传(好看)

1.首先在html页面的model中写如下代码:

<div>
	<label class="col-sm-4 ">广告图片:</label>
	<div class="col-sm-8">
		<img  id="carPicImg" name="carPicImg" width="100%" onclick="fileSelect()"/>
    </div>
 </div>
 <div id="fileDiv" hidden="hidden">
		<label class="col-sm-2 control-label">图片上传:</label>
    	 <div class="col-sm-10">
       	 	<input type="file" id="file" name="file" />
  		</div>
 </div>

2.在js中写:
//页面初始化:

$(document).ready(function () {
//模态框图片上传,选择图片,前台显示
	document.querySelector("#file").onchange = function(){
   	console.log(this.value);
    document.querySelector("#carPicImg").src = getFileUrl(this.id);
    searchList()
};
});

//列表回显部分代码:

var _columns = [
    {
        "data": "pic",
        render: function (data, type, row, meta) {
            if(data){
                return '<img src="'+getCarModelImgBaseUrl()+data+'" class="carPic" />';
            }else{
                return "——";
            }
        }
    },
    {
    data: 'commond',
    render: function (data, type, row, meta) {
        var btnStr = "";
        btnStr = btnStr + '<button type="button" class="btn btn-outline btn-info" style="margin-right: 15px" onclick="editModal(\'' + meta.row + '\')">编辑</button>';
        btnStr = btnStr + ' <button type="button" class="btn btn-outline btn-danger" onclick="doDel(\'' + meta.row + '\')">删除</button>';
        return btnStr;
    },
    "orderable" :false
}
];




function searchList() {
var adSupplier = $("#adSupplierSearch").val();
var searchArray = {
    "adSupplier":adSupplier
};

var buttons = [];
var columnOrder = {};
dataTableMain("advertisementTable","/advertisement/getAdList", _columns, buttons, searchArray,columnOrder);

}

//重点是以下函数

/*图片上传*/
//点击图片关联点击文件上传组件
function fileSelect(){
    $("#file").click();
}

//获取本地需上传的图片路径,预览所选图片
function getFileUrl(sourceId) {
    var url;
    if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
        url = document.getElementById(sourceId).value;
    } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    }
    return url;
}

function getCarModelImgBaseUrl(){
    return "http://39.105.31.168/shareCarPic";
}

3.在对应controller加

	 Map<String, Object> map = new HashMap<>();
	 String pic = "";
	 Map fileMap = uploadServiceImpl.upload(request, file);
	 if (fileMap != null && fileMap.size() > 0) {
		 pic = (String) fileMap.get("fileUrl");
	 }

contoller中全部代码

	 /**
     * 添加编辑
     */
    @RequestMapping(value = "/addAdList", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult addSystemUser(HttpServletRequest request, TshareAdvertisement tshareAdvertisement, MultipartFile file) {
        try {
            Map<String, Object> map = new HashMap<>();
            String pic = "";
            Map fileMap = uploadServiceImpl.upload(request, file);
            if (fileMap != null && fileMap.size() > 0) {
                pic = (String) fileMap.get("fileUrl");
            }

            if (StringUtils.isEmpty(tshareAdvertisement.getId())) {
                //添加
                if (StringUtils.isEmpty(tshareAdvertisement.getAdSupplier())) {
                    return new JSONResult(null, 103, "请输入广告提供商");
                }
                tshareAdvertisement.setId(null);
                tshareAdvertisement.setAdSupplier(tshareAdvertisement.getAdSupplier());
                tshareAdvertisement.setCreateTime(new Date());
                tshareAdvertisement.setUpdateTime(new Date());
                tshareAdvertisement.setDelFlag("0");
                tshareAdvertisement.setUrl(pic);
                tshareAdvertisement.setPic(pic);
                tshareAdvertisementRepository.save(tshareAdvertisement);
            } else {
                //编辑
                Query query = new Query(Criteria.where("id").is(tshareAdvertisement.getId()));
                Update update = new Update();
                update.set("updateTime",new Date());
                update.set("url", pic);
                update.set("pic", pic);
                mongoTemplate.findAndModify(query, update, TshareAdvertisement.class);
            }

            return new JSONResult(map, 0, "成功");
        } catch (Exception e) {
            return new JSONResult(null, 101, "失败");
        }
    }

4.其中要写的upload类:

 //图片上传
    public Map<String, Object> upload(HttpServletRequest request, MultipartFile file) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (file == null) {
                throw new IllegalArgumentException("参数异常");
            }
            String filePath = request.getSession().getServletContext().getRealPath("/") + "static/upload/";
            //创建上传目录
                //String filePath ="/static/upload/";

            Date time = new Date();
            SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd");
            String subPath = myFmt.format(time);
            filePath = filePath + subPath;

            File targetFolder = new File(filePath);
            if (!targetFolder.exists()) {
                targetFolder.mkdirs();
            }
        //生成文件名称
            String name = file.getOriginalFilename();
            String fileName = DigestUtils.md5Hex(time.getTime() + name.substring(0, name.lastIndexOf('.'))) + "." + name.substring(name.lastIndexOf(".") + 1);

       //创建接收对象
            File targetFile = new File(filePath, fileName);
        //保存
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(targetFile));
            out.write(file.getBytes());
            out.flush();
            out.close();
            String fileUrl = "/static/upload/" + myFmt.format(time) + "/" + fileName;
            map.put("fileUrl", fileUrl);
        LOGGER.info("上传了" + targetFolder + " " + fileName);
        return map;
    } catch (Exception e) {
        return map;
    }

}

finish!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 实现项目全局编码过滤器功能: 在web.xml文件中配置过滤器: ``` <filter> <filter-name>EncodingFilter</filter-name> <filter-class>com.example.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 创建一个编码过滤器类EncodingFilter,实现Filter接口,在doFilter方法中设置编码为UTF-8: ``` public class EncodingFilter implements Filter { public void init(FilterConfig config) throws ServletException {} public void destroy() {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); } } ``` 2. 实现登录过滤器功能: 在web.xml文件中配置过滤器: ``` <filter> <filter-name>LoginFilter</filter-name> <filter-class>com.example.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/admin/*</url-pattern> </filter-mapping> ``` 创建一个登录过滤器类LoginFilter,实现Filter接口,在doFilter方法中判断用户是否已经登录,如果已经登录则放行,否则重定向到登录页面: ``` public class LoginFilter implements Filter { public void init(FilterConfig config) throws ServletException {} public void destroy() {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; HttpSession session = req.getSession(false); if (session == null || session.getAttribute("user") == null) { resp.sendRedirect(req.getContextPath() + "/login.jsp"); return; } chain.doFilter(request, response); } } ``` 3. 在商品列表上增加“添加”按钮,并实现商品图片上传功能: 在商品列表页面中增加一个“添加”按钮,点击按钮弹出一个模态框(利用Bootstrap创建),在模态框中有一个商品表单用于填写商品信息,并且可以上传商品图片。当用户点击“添加”按钮时,将商品信息和图片上传到服务器并保存到数据库中,然后重新加载商品列表页面,展示添加后的商品信息。 实现步骤: 1. 在商品列表页面中添加“添加”按钮,用于弹出模态框: ``` <button class="btn btn-primary" data-toggle="modal" data-target="#addProductModal">添加</button> ``` 2. 创建一个模态框,用于填写商品信息和上传商品图片: ``` <div class="modal fade" id="addProductModal" tabindex="-1" role="dialog" aria-labelledby="addProductModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="addProductModalLabel">添加商品</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <form id="addProductForm" enctype="multipart/form-data"> <div class="form-group"> <label for="productName">商品名称</label> <input type="text" class="form-control" id="productName" name="productName"> </div> <div class="form-group"> <label for="productPrice">商品价格</label> <input type="text" class="form-control" id="productPrice" name="productPrice"> </div> <div class="form-group"> <label for="productImage">商品图片</label> <input type="file" class="form-control-file" id="productImage" name="productImage"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" id="addProductBtn">添加</button> </div> </div> </div> </div> ``` 3. 在客户端使用Ajax技术将商品信息和图片上传到服务器: ``` $('#addProductBtn').click(function() { var formData = new FormData($('#addProductForm')[0]); $.ajax({ url: 'AddProductServlet', type: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data) { location.reload(); }, error: function() { alert('添加商品失败'); } }); }); ``` 4. 在服务器端创建一个Servlet(AddProductServlet),用于接收并保存商品信息和图片: ``` public class AddProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String productName = request.getParameter("productName"); double productPrice = Double.parseDouble(request.getParameter("productPrice")); Part productImagePart = request.getPart("productImage"); InputStream productImageInputStream = productImagePart.getInputStream(); // 保存商品信息和图片到数据库中 // ... response.getWriter().println("添加商品成功"); } } ``` 5. 在商品列表页面中重新加载商品信息: ``` success: function(data) { location.reload(); }, ``` 这样就完成了在商品列表上增加“添加”按钮,并实现商品图片上传功能的需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值