操作文件
跳转到“操作文件”原生HTML表单通常用input type="file"选择文件,以POST和multipart/form-data提交文件内容。脚本也可通过FormData/fetch、拖放等方式处理用户授权提供的文件;不是所有上传都只能由原生表单发起。下面表单action为演示端点,实际上传需配套服务器。
<form id="upload-form" action="/upload" method="post" enctype="multipart/form-data"> <input id="test-image-file" name="image" type="file" accept="image/jpeg,image/png,image/gif"> <button type="submit">上传</button></form><pre id="test-file-info"></pre><div id="test-image-preview" style="width:240px;height:160px;background-size:contain;background-repeat:no-repeat"></div>脚本不能用非空value指定任意本地路径(会抛InvalidStateError),但可用空字符串清除选择。value可能呈现C:\fakepath\文件名,不能据此获得真实路径;读取用户选中文件用files。accept、扩展名和File.type都是客户端提示,不能代替服务器对格式、大小及内容的检查。
以下代码在上述HTML之后执行。扩展名函数替代原稿顶层return false的非法写法;只用于友好提示,大小上限5MiB是本例选择。
function hasImageExtension(file) { return /\.(jpe?g|png|gif)$/i.test(file.name);}const fileInput = document.getElementById('test-image-file');const info = document.getElementById('test-file-info');const preview = document.getElementById('test-image-preview');let selectionVersion = 0;fileInput.addEventListener('change', function () { const version = ++selectionVersion; preview.style.backgroundImage = ''; const file = fileInput.files[0]; if (!file) { info.textContent = '没有选择文件'; return; } info.textContent = `文件: ${file.name}\n大小: ${file.size}\n修改: ${file.lastModified}`; const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']; if (!hasImageExtension(file) || !allowedTypes.includes(file.type)) { info.textContent += '\n仅预览JPEG/PNG/GIF;扩展名和MIME不构成真实性证明。'; return; } if (file.size > 5 * 1024 * 1024) { info.textContent += '\n本例预览上限为5MiB。'; return; } const reader = new FileReader(); reader.onload = function () { if (version !== selectionVersion) return; // 避免旧选择覆盖新结果 if (typeof reader.result === 'string') { preview.style.backgroundImage = `url("${reader.result}")`; } }; reader.onerror = function () { if (version === selectionVersion) info.textContent += '\n读取失败'; }; reader.onabort = function () { if (version === selectionVersion) info.textContent += '\n读取已取消'; }; reader.readAsDataURL(file);});FileReader事件异步触发,不能在readAsDataURL下一行假定结果已就绪;不等于JavaScript所有任务都异步。文件名写入textContent,避免当HTML解释。上例只做预览筛选,不阻止表单提交,也不能保证浏览器一定能解码伪造MIME的图片;服务器必须独立验证。
若改用fetch发送FormData,不要手写multipart Content-Type,浏览器需要自动生成boundary。参考:文件输入、使用FileReader、使用FormData。