关于文件上传的ajax交互

首先我们来了解一下上传文件

<input type="file">

input的file常用上传类型

后缀名       MIME名称
*.3gpp    audio/3gpp, video/3gpp
*.ac3    audio/ac3
*.asf       allpication/vnd.ms-asf
*.au           audio/basic
*.css           text/css
*.csv           text/csv
*.doc    application/msword    
*.dot    application/msword    
*.dtd    application/xml-dtd    
*.dwg    image/vnd.dwg    
*.dxf      image/vnd.dxf
*.gif            image/gif    
*.htm    text/html    
*.html    text/html    
*.jp2            image/jp2    
*.jpe       image/jpeg
*.jpeg    image/jpeg
*.jpg          image/jpeg    
*.js       text/javascript, application/javascript    
*.json    application/json    
*.mp2    audio/mpeg, video/mpeg    
*.mp3    audio/mpeg    
*.mp4    audio/mp4, video/mp4    
*.mpeg    video/mpeg    
*.mpg    video/mpeg    
*.mpp    application/vnd.ms-project    
*.ogg    application/ogg, audio/ogg    
*.pdf    application/pdf    
*.png    image/png    
*.pot    application/vnd.ms-powerpoint    
*.pps    application/vnd.ms-powerpoint    
*.ppt    application/vnd.ms-powerpoint    
*.rtf            application/rtf, text/rtf    
*.svf           image/vnd.svf    
*.tif         image/tiff    
*.tiff       image/tiff    
*.txt           text/plain    
*.wdb    application/vnd.ms-works    
*.wps    application/vnd.ms-works    
*.xhtml    application/xhtml+xml    
*.xlc      application/vnd.ms-excel    
*.xlm    application/vnd.ms-excel    
*.xls           application/vnd.ms-excel    
*.xlt      application/vnd.ms-excel    
*.xlw      application/vnd.ms-excel    
*.xml    text/xml, application/xml    
*.zip            aplication/zip    
*.xlsx     application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

accept属性

只能选择png和gif图片

<input id="fileId1" type="file" accept="image/png,image/gif" name="file" />

multiple属性

多文件上传

<input id="fileId2" type="file" multiple="multiple" name="file" />

获取file的内容

这里要用到change()函数,当元素的值发生改变时,会发生 change 事件。

$('input[type="file"]').change(function() {
    file = this.files[0];
});

file获取出来的内容

File {name: "DSC03891.JPG", lastModified: 1451217306000, lastModifiedDate: Sun Dec 27 2015 19:55:06 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 3866624…}lastModified: 1451217306000lastModifiedDate: Sun Dec 27 2015 19:55:06 GMT+0800 (中国标准时间)name: "DSC03891.JPG"size: 3866624type: "image/jpeg"webkitRelativePath: ""__proto__: File

我们需要将图片文件转换成二进制流的方式传给后台,这里我介绍两种方式

FileReader

这一篇博客对FileReader的使用介绍得很详尽,请参看
http://blog.csdn.net/zk437092645/article/details/8745647/

FormData

FormData有两种用法

  • 提交表单数据

提交表单还有一个方法是serialize(),但这个方法不能上传文件

使用方法

  1. 在html的form标签里添加 enctype ="multipart/form-data",这个很重要,没有这个后面所有都没效果
<form class="form-horizontal" id="productform" enctype ="multipart/form-data">
  1. 在html表单的input中添加name属性,name对应数据库中的字段名
<input type="text" name="productName">
<input type="text" name="productContent">
  1. ajax交互
$('#submit').click(function(){
    var data = new FormData($('#productform')[0]);//[0]必须要
    $.ajax({
        type:"POST",
        url:"http://localhost/blog/management/insertProduct",
        data:data,
                async:false,
                cache:false,
                contentType:false,
                processData:false,
        success:function() {
                alert("保存成功!");
        },
        error:function() {
                alert("保存失败!");
                console.log(productType);
        }

    })
        
        
});
  • 直接使用FormData

FormData也可以直接使用而不是提交整个表单

<input type="file" name="picture" accept=".jpg,.png"
<input type="button" name="" value="提交" class="submit">
$('.submit').click(function() {
            var bannerIdText = $(this).closest('div').find(".bannerId").text();
            console.log($(".bannerId").html());
            var data = new FormData();
            data.append("picture",file);
            console.log(bannerIdText);
            data.append("bannerId",bannerIdText);
            console.log(data);
            $.ajax({
                type:"POST",
                url:" http://localhost/blog/management/updateBanner",
                data:data,
                            async:false,
                            cache:false,
                            contentType:false,
                            processData:false,
                            enctype: 'multipart/form-data',//没有了在form声明处理方式,就必须在这里声明
                success:function(data) {
                    alert("保存成功!");
                    console.log(data);
                },
                error:function() {
                    alert("保存失败!");
                }
           })
        }); 

FormData的append参数说明

data.append(数据库字段名,你添加的东西名字)

最后如果前端成功的将数据发给后台了,你可以在network中看到这样的信息。


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,908评论 18 139
  • 上传文件已经是个已经成熟的前端技术,目前开源的拿来即用的前端上传插件也比较多,诸如:Web Uploader、JS...
    清晓凝露阅读 11,455评论 0 22
  • 最近项目需要使用 Angular,对于初学 Angular 的我只能硬着头皮上了,项目中有一个需求是文件上传,磕磕...
    虽万万人吾往矣阅读 18,343评论 3 20
  • 背景描述 有这么一个需求:一个表单,有十几个input,一个文件上传的input,可以上传一张图片。 要求上传图片...
    Java_or_PHP阅读 4,569评论 0 5
  • 说起录屏的需求是从自己学习 Keyote、Final Cut Por网上的教程开始的,平时喜欢鼓捣软件,有朝一日自...
    阿吉先生ok阅读 32,236评论 5 6