zoukankan      html  css  js  c++  java
  • H5表单提交上传图片

    jsp部分

    <link rel="stylesheet" href="${ctx }/static/uploadify/css/html5uploader.css" />
    <link rel="stylesheet" href="${ctx}/static/uploadify/css/webuploader.css" />
    <link rel="stylesheet" href="${ctx}/static/css/weui.css" />
    <script type="text/javascript" src="${ctx }/static/js/md5.js"></script>
    <script src="${ctx }/static/js/jquery.html5uploader.js"
    type="text/javascript"></script>  //上传js

    <script type="text/javascript">

    //提交表单
    function saveAdd() {
    var title = $("#title").val();
    var reporter = $("#reporter").val();
    var organization = $("#organization").val();
    var address = $("#address").val();
    var reason = $("#reason").val();
    var urgency = $("#urgency").val();
    var grade = $("#grade").val();
    var memo = $("#memo").val();
    var str = '{"title":"' + title + '", "reporter":"' + reporter           //拼接json串
    + '", "organization":"' + organization
    + '", "address":"' + address
    + '", "reason":"' + reason
    + '", "urgency":"' + urgency
    + '", "grade":"' + grade
    + '", "memo":"' + memo
    + '", "heexanteriskattachment":[';
    var strAttachment = '';
    $(".addAttachment_").each(                                              //循环上传图片列表
    function() {
    var filename = $(this).parent().find("td:eq(0)").text();
    var path = $(this).parent().find("#earlypath").val();
    var uploader = $(this).parent().find("#uploaderId").val();
    var uploadDatetime = $(this).parent().find(".uploadDatetime").val();
    alert(uploader);
    strAttachment += '{"filename":"' + filename
    + '","path":"' + path
    + '","uploader":"' + uploader
    + '","uploaddatetime":"' + uploadDatetime
    + '"}';
    });
    str += strAttachment;
    str += ']}';


    $.ajax({
    url:'${ctx}/exanterisk/addnewinfo',
    type:'post',
    cache:false,
    data:{
    str:str
    },
    error:function(){
    alertMsg.warn('网络错误!');
    },
    success:function(data){
    if(data==0){
    alertMsg.warn("添加失败");
    }
    if(data==1){
    alertMsg.correct("提交成功");
    navTab.closeCurrentTab();
    navTab.openTab("heexanteriskhandle", "${ctx}/exanterisk/handle", { title:"事前风险处理", fresh:true, data:{page:1,rows:20} });
    }
    }
    });
    }

    //光标事件
    function s(e,a){
    if ( e && e.preventDefault )
    e.preventDefault();
    else
    window.event.returnValue=false;
    a.focus();
    }

    $(function() {                                                   //上传图片
    $('#uploadearly').html5uploader(
    {
    auto : true,
    multi : true,
    removeTimeout : 99999999,
    url : '${ctx}/exanterisk/upload',
    onUploadStart : function() {
    //alert('开始上传');
    },
    onInit : function() {
    //alert('初始化');
    },
    onUploadComplete : function() {
    //alert('上传完成');
    },
    onUploadSuccess : function(file, data,respone) {

    var obj = JSON.parse(data);

    var root = "${ctx}"+ (obj.path).replace(/["""]/g, "");              //路径
    var str="";
    str += '<tr class="addproject">';
    str += '<td align="center" class="addAttachment_" id="earlyfilename">'+obj.filename+'<input style="100px" id="earlypath" type="hidden" name="path" class="path" value="'+root+'"></td>';
    str += '<td align="center" id="earlyuploader" value="'+obj.uploader+'">'+obj.uploadername+'<input style="100px" id="uploaderId" type="hidden" name="uploader" class="uploader" value="'+obj.uploader+'"></td>';
    str += '<td align="center" id="earlyuploadDatetime" value="'+obj.uploaddatetime+'">'+obj.uploaddate+'<input style="100px" id="uploadDatetime" type="hidden" name="uploadDatetime" class="uploadDatetime" value="'+obj.uploaddatetime+'"></td>';
    str += '<td align="center"><a class="btn btn-danger btn-sm" onclick="deladdproject(this)" ><i class="iconfont" value="删除" style="font-size: 12px;">删除</i></a></td></tr>';

    $("#addtbody").append(str);             //上传成功后返回对象动态添加到图片表格列表中
    }

    });

    });

    function deladdproject(tag) {
    $(tag).parent().parent().remove();
    }

    </script>

    //上传图片按钮

    <div class="col-xs-12 col-md-12">
    <label style=" 80px;font-size: 13px;font-weight:bold;">相关附件:</label>
    <label id="uploadearly"><input class="uploadfile" style="visibility:hidden;" name="fileselect[]" multiple="" type="file"><a href="javascript:void(0)" class="uploadfilebtn">选择文件</a><ul class="filelist"></ul></label>
    </div>

    ----------------------------------------------------------------------------------------------------------------------------------------------------

    controller部分

    @RequestMapping("upload")
    @ResponseBody    //返回json串
    public HeExAnteRiskAttachment upload(HttpServletRequest request,
    HttpServletResponse response,HttpSession session) {
    String resultName = "";
    String newFileName = "";
    HeExAnteRiskAttachment heexanteriskattachment=new HeExAnteRiskAttachment();
    // 设置保存路径为tomcat下的...
    ServletContext context = request.getSession().getServletContext();

    SimpleDateFormat dfday = new SimpleDateFormat("yyyyMMdd");
    String relativePath = "/upload/" + dfday.format(new Date());
    String savePath = context.getRealPath(relativePath);

    File f = new File(savePath);
    // 创建文件夹
    if (!f.exists()) {
    f.mkdirs();
    }          //文件保存路径

    // 文件流
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Iterator item = multipartRequest.getFileNames();
    while (item.hasNext()) {
    String fileName = (String) item.next();
    MultipartFile file = multipartRequest.getFile(fileName);
    //截取不带扩展名的文件名
    fileName = file.getOriginalFilename().substring(0,
    file.getOriginalFilename().lastIndexOf("."));
    // 检查扩展名
    String fileExt = file.getOriginalFilename()
    .substring(file.getOriginalFilename().lastIndexOf(".") + 1)
    .toLowerCase();
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    // 新文件名为原名+日期+随机数
    newFileName = df.format(new Date()) + "_"
    + new Random().nextInt(1000) + "." + fileExt;
    heexanteriskattachment.setFilename(newFileName);
    resultName = resultName + newFileName + ";";
    try {
    //MultipartFile转化为File并输出
    File uploadedFile = new File(savePath, newFileName);
    file.transferTo(uploadedFile);
    uploadedFile.createNewFile();
    } catch (Exception e) {
    e.printStackTrace();
    }             //保存文件
    }
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String strurl = relativePath +"/"+resultName;
    User user =(User)session.getAttribute("user");
    if(user!=null){
    heexanteriskattachment.setUploadername(user.getUsername());
    heexanteriskattachment.setUploader(user.getId());
    }
    Date date = new Date();
    heexanteriskattachment.setUploaddatetime(new Date());
    heexanteriskattachment.setPath(strurl);
    heexanteriskattachment.setUploaddate(df.format(date));
    return heexanteriskattachment;
    }

    ------------------------------------------------------------------------

    //添加事前风险报告
    @RequestMapping(value = "/addnewinfo", method = RequestMethod.POST)
    @ResponseBody
    public String addShop(
    @RequestParam(value = "str") String str,                  //接收前端的json串
    HttpServletRequest request) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    HeExAnteRisk heexanterisk = mapper.readValue(str, HeExAnteRisk.class);          //json串转对象
    try{
    exanteriskservice.insertheexanterisk(heexanterisk);
    }catch(Exception e){
    return "0";
    }
    return "1";
    }

    -----------------------------------------------------------------------------------------------------

    Service部分           存储到数据库方法

    public void insertheexanterisk(HeExAnteRisk heexanterisk) {
    List<HeExAnteRiskAttachment> list =null;
    if (heexanterisk != null) {
    heexanteriskmapper.insertSelective(heexanterisk);
    list = heexanterisk.getHeexanteriskattachment();
    if(list!=null){
    for(HeExAnteRiskAttachment heexanteriskattachment:list){
    heexanteriskattachment.setReportid(heexanterisk.getId());                //useGeneratedKeys="true" keyProperty="id接收字段"   返回主键

    heexanteriskattachmentmapper.insertSelective(heexanteriskattachment);
    }
    }

    }


    }

    -------------------------------------------------------------------------------------------------------------------------------------------

    回显图片jsp和保存附件controller

    <script type="text/javascript">
    $(".weui_uploader_status_clear").each(
    function() {
    $(this).click(function() {
    urlimg = $(this).parent().css(
    'background-image');
    //去除url();
    urlimg = urlimg.substr(4, urlimg.length - 5);


    //删除本
    $(this).parent().remove();

    //更新uploadedFileHtml
    var uploadedFileHtml = "";
    $("#divAttachemt >*").each(
    function() {
    var baseszie = this.baseURI.length;
    urlimg = $(this).css(
    'background-image');
    urlimg = urlimg.substr(baseszie-4,
    urlimg.length +1 - baseszie);

    uploadedFileHtml = uploadedFileHtml
    + ";" + urlimg;

    });
    $("#uploadedFile").val(uploadedFileHtml);

    })
    });

    function delimage(obj){


    urlimg = $(obj).parent().css(
    'background-image');
    //去除url();
    urlimg = urlimg.substr(4, urlimg.length - 5);
    //layer.msg(urlimg);

    //删除本
    $(obj).parent().remove();

    //更新uploadedFileHtml
    var uploadedFileHtml = "";
    $("#divAttachemt >*").each(
    function() {
    var baseszie = this.baseURI.length;
    urlimg = $(this).css(
    'background-image');
    urlimg = urlimg.substr(baseszie-4,
    urlimg.length +1 - baseszie);

    uploadedFileHtml = uploadedFileHtml
    + ";" + urlimg;

    });
    $("#uploadedFile").val(uploadedFileHtml);
    }

    $(function() {
    $('#upload').html5uploader(
    {
    auto : true,
    multi : true,
    removeTimeout : 99999999,
    url : '${ctx}/user/upload',
    onUploadStart : function() {
    //alert('开始上传');
    },
    onInit : function() {
    //alert('初始化');
    },
    onUploadComplete : function() {
    //alert('上传完成');
    },
    onUploadSuccess : function(file, filename) {

    var root = "${ctx}"+ filename.replace(/["""]/g, "");

    var str = '<li class="weui_uploader_file" style="background-image:url('
    + root
    + ')"> <div class="weui_uploader_status_clear" onclick="javacript:delimage(this)" > <i class="weui_icon_clear" color="red"></i> </div></li>';

    $("#divAttachemt").append(str);
    //更新uploadedFileHtml 
    var uploadedFileHtml = "";
    $("#divAttachemt >*").each(
    function() {
    var baseszie = this.baseURI.length;

    urlimg = $(this).css('background-image');

    urlimg = urlimg.substr(baseszie-4,
    urlimg.length +1 - baseszie);

    uploadedFileHtml = uploadedFileHtml + ";"
    + urlimg;

    });

    $("#uploadedFile").val(uploadedFileHtml);
    }

    });

    });


    </script>

    //controller

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public String addUser(@RequestParam(value = "userName") String userName,
    @RequestParam(value = "loginName") String loginName,
    @RequestParam(value = "password") String password,
    @RequestParam(value = "departmentId",defaultValue="1") int departmentId,
    @RequestParam(value = "positionId",defaultValue="0",required=false) int positionId,
    @RequestParam(value = "sex",defaultValue="0") int sex,
    @RequestParam(value = "address") String address,
    @RequestParam(value = "tel") String tel,
    @RequestParam(value = "text") String text,
    @RequestParam(value = "uploadedFile", required = false) String uploadedFile,
    @RequestParam(value = "certificateName", required = false) String certificateName,
    HttpServletRequest request) throws ParseException{
    String flag="ok";
    User a = userService.findUserByLoginName(loginName);
    List<User> b = userService.findUserByUserName(userName);
    if(a!=null){
    flag="existLogin";
    }else if(b!=null&&b.size()>0){
    flag="existName";
    }else{
    User user = new User();
    user.setAddress(address);
    user.setDepartmentid(departmentId);
    user.setLoginname(loginName);
    user.setPassword(password);
    user.setPositionid(positionId);
    user.setSex(sex);
    user.setTel(tel);
    user.setMemo(text);
    user.setStatus(1);
    user.setUsername(userName);

    // 保存附件
    List<UserAttachment> achlist = new ArrayList<UserAttachment>();
    String[] strfiles = uploadedFile.split(";");
    for (String file : strfiles) {
    if (file.length() > 4) {
    UserAttachment ach = new UserAttachment();
    file = file.trim().startsWith("/")?file:"/"+file;
    ach.setPath(file);
    String fileName = file.substring(file.lastIndexOf("/") + 1);
    ach.setFilename(fileName);
    ach.setCertificatename(certificateName);
    achlist.add(ach);
    }
    }

    userService.addUser(user,achlist);
    }
    return flag;
    }

    当能力支撑不了野心时,就该静下心来学习!
  • 相关阅读:
    Kubernetes 系列(八):搭建EFK日志收集系统
    Kubernetes 系列(七):持久化存储StorageClass
    Kubernetes 系列(六):持久化存储 PV与PVC
    .Net Core自动化部署系列(三):使用GitLab CI/CD 自动部署Api到Docker
    Ocelot自定义管道中间件
    生产环境项目问题记录系列(二):Docker打包镜像Nuget包因权限问题还原失败
    .Net Core 商城微服务项目系列(十四):分布式部署携程Apollo构建配置中心
    IT人该如何未雨绸缪,不断提升自己的竞争力?同时尽量避免风险?
    Session跟Cookie简单的理解
    软件测试中高级面试提问
  • 原文地址:https://www.cnblogs.com/1234cjq/p/6169801.html
Copyright © 2011-2022 走看看