• input type="file 将图片传给后台


    今天需要做一个移动端的调查问卷,不止要提交标题,还需要提交配图。(黑人问号脸.jpg)

    此时,对于一个菜鸡,无疑把我给难住了,问完度娘后选择使用new FormData()方法。

    直接正片吧:

    <a class="file">
      <form enctype="multipart/form-data">
        <input type="file" id="imgFile" name="files" accept="image/jpg,image/jpeg,image/png,image/PNG" />
      </form>
    </a>

    var formFile = new FormData();

    $('.file').change(function(){

      var imgfile = document.querySelector('#imgFile');//获取input
      var file = imgfile.files[0]; //获取文件对象
      formFile.append("uploadFile", file); //加入文件对象
    })

    // 在其他函数内把其他的参数也添加进去,这里就举个栗子吧 ps:查看指定内容 formFile.get('sharereport.title') 删除指定内容 formFile.delete('sharereport.title')

    formFile.append("sharereport.describes",sharereport.describes);
    formFile.append("sharereport.username",sharereport.username);
    formFile.append("sharereport.phones",sharereport.phones);
    formFile.append("sharereport.title",sharereport.title);

    //传给后台

    $.ajax({
      type:"post",
      url:"",
      data:formFile,

      //是否预处理,默认值为true,这里改成false
      processData:false,

      //是否设置内容,默认值为true,这里改成false
      contentType:false,
      success:function(res){
        alert('提交成功');
      },
      error:function(data){
        alert('提交失败');
      }
    });

    提交成功,数据成功传给后台

    注意:提交后这些数据还保留在formFile里面。如果用户再操作就会有把原来的数据也发送出去,此时可以在alert()后formFile = new FormData();或者跳转页面以及关闭页面。

  • 相关阅读:
    检测主机存活
    centos7 安装python3
    zbb20180103 git 配置用户名和邮箱
    zbb20171215 git 版本回退
    zbb20171215 bootstrap model 模态框
    zbb20171215 MyBatis报错: Parameter '*' not found. Available parameters are [1, 0, param1, param2]
    zbb20171215 thymeleaf th:attr
    zbb20171215ztree ztree出现$.fn.zTree is undefined错误的解决办法
    zbb20171215 bootstrap 日期控件.rar
    zbb20171215 oracle replace 替换单引号
  • 原文地址:https://www.cnblogs.com/BluceLee/p/15247086.html
Copyright © 2020-2023  润新知