HTML5的 input:file上传类型控制

本文介绍了HTML5中input:file元素的使用,包括accept属性限制上传文件类型,multiple属性实现多文件选择。还详细讲解了如何通过AJAX进行文件上传,包括获取文件列表,创建FormData对象,以及使用XMLHttpRequest发送POST请求。同时,提到了服务器端接收到文件后的处理方式。最后,给出了一个关于input[type=file]样式美化和上传按钮美化的话题链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、input:file属性

属性值有以下几个比较常用:

accept:表示可以选择的文件MIME类型,多个MIME类型用英文逗号分开,常用的MIME类型见下表。

multiple:是否可以选择多个文件,多个文件时其value值为第一个文件的虚拟路径。

1、accept

只能选择png和gif图片

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

2、multiple

多文件上传

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

3、常用MIME类型

后缀名       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

二、样式美化

请看博客:css input[type=file] 样式美化,input上传按钮美化 css input[type=file] 样式美化,input上传按钮美化

三、AJAX上传文件

在说到ajax上传文件。ajax上传的时候,需要获得input:file选择的文件(可能为多个文件),获取其文件列表为:

// input标签的files属性
document.querySelector("#fileId").files
// 返回的是一个文件列表数组

获得的文件列表,然后遍历插入到表单数据当中。即:

// 获得上传文件DOM对象
var oFiles = document.querySelector("#fileId");


// 实例化一个表单数据对象
var formData = new FormData();



// 遍历图片文件列表,插入到表单数据中
for (var i = 0, file; file = oFiles[i]; i++) {
    // 文件名称,文件对象
    formData.append(file.name, file);
}

获得表单数据之后,就可以用ajax的POST上传。

// 实例化一个AJAX对象
var xhr = new XMLHttpRequest();
xhr.onload = function() {
    alert("上传成功!");
}
xhr.open("POST", "upload.php", true);

// 发送表单数据
xhr.send(formData);

上传到服务器之后,获取到文件列表为:

Array
(
    [jpg_jpg] => Array
        (
            [name] => jpg.jpg
            [type] => image/jpeg
            [tmp_name] => D:\xampp\tmp\phpA595.tmp
            [error] => 0
            [size] => 133363
        )

    [png_png] => Array
        (
            [name] => png.png
            [type] => image/png
            [tmp_name] => D:\xampp\tmp\phpA5A6.tmp
            [error] => 0
            [size] => 1214628
        )

)

在服务端循环遍历这个数组就可以上传文件了。

当你需要将用户选择的文件通过POST请求发送到服务器时,通常涉及到前端HTMLJavaScript以及后端API的交互。以下是步骤: 1. **HTML部分**: 使用`<input type="file" id="fileInput">`创建一个文件输入框,允许用户选择文件。 2. **JavaScript部分 (前端)** - 添加事件监听器处理文件选择: ```javascript document.getElementById('fileInput').addEventListener('change', function(e) { const file = e.target.files[0]; // 获取用户选择的第一个文件 // ...后续处理文件并发起POST请求 }); ``` - 使用`FormData`对象构建POST数据,它支持二进制数据,包括文件: ```javascript const formData = new FormData(); formData.append('file', file); ``` 3. **发起POST请求**: - 使用XMLHttpRequest或fetch API向后端服务器发送POST请求: ```javascript const xhr = new XMLHttpRequest(); xhr.open('POST', '/api/upload', true); // 替换为实际的API地址 xhr.onload = function() { if (xhr.status === 200) { // 检查响应状态 console.log('文件上传成功'); } else { console.error('文件上传失败'); } }; xhr.send(formData); ``` 或者使用fetch: ```javascript fetch('/api/upload', { method: 'POST', body: formData, headers: {'Content-Type': 'multipart/form-data'} }) .then(response => response.ok ? console.log('文件上传成功') : console.error('文件上传失败')) .catch(error => console.error('错误:', error)); ``` 4. **后端处理**: 后端收到POST请求后,解析`multipart/form-data`类型的请求体,读取文件内容,并保存到数据库或其他存储系统中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值