HTML网页中,点击按钮就直接弹出文件选择框后上传文件:
需要jquery支持。
原理:
使用一个隐藏的file input框,外加一个按钮,点击按钮后,自动触发file input框的点击事件弹出文件选择框。然后在file input的onchange中,自动调用上传文件的代码。
<input type="file" name="file" id="file" onchange="uploadFile();" style="display:none"><i class="fa fa-picture-o" aria-hidden="true" onclick="$('#file').trigger('click');"></i>
<script>
function uploadFile() {
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url : 'upload',
type : 'POST',
data : formData,
contentType: false,
processData: false,
dataType: 'json',
clearForm: true,
success: function(data) {
if (data.result === "OK") {
Toast('上传成功', 5000);
} else {
Toast('上传失败:<br/>' + data.msg, 5000);
}
$('#file').val("");
},
error: function(data, status, e) {
$('#file').val("");
Toast('上传失败:<br/>' + e, 5000);
}
});
}
</script>
ThinkPHP6.0, 服务器端 Controller 代码:
public function upload($to) {
if (!session('user')) {
$this->ajaxReturn(["auth" => "NoAuth"]);
}
try {
$file = request()->file('file');
validate(['file' => ['fileSize' => 50 * 1024 * 1024, 'fileExt' => 'gif,jpg,png,jpeg,mp4']])->check(['file' => $file]);
$savename = \think\facade\Filesystem::putFile('image', $file);
$url = "/file?url=" . $savename;
if (strtolower($file->getOriginalExtension()) == "mp4")
$mtext = "<video controls src='" . $url . "'>";
else
$mtext = "<img src='" . $url . "'>";
$data = ["mfrom" => session('uid'), 'mtext' => $mtext, 'mto' => $to];
Db::name('tb_msg')->insert($data);
$ret['result'] = "OK";
$ret['url'] = $url;
$this->ajaxReturn($ret);
} catch (\Exception $e) {
$this->ajaxReturn(["result" => "error", "msg" => $e->getMessage()]);
}
}