我有下一张表格:
<form action="/upload" enctype="multipart/form-data" method="POST">
<input name="example" type="file">
<input type="submit" value="Upload">
</form>
在服务器端,我看到大小为零的文件已上传:
-----------------------------23370864791729106148808009039
Content-Disposition: form-data; name="example"; filename=""
Content-Type: application/octet-stream
-----------------------------23370864791729106148808009039--
如何检查用户没有为此file
字段选择任何内容?
答案 0 :(得分:0)
在您的输入字段中添加required
,以确保元素已上传。
<form action="/upload" enctype="multipart/form-data" method="POST">
<input required name="example" type="file">
<input type="submit" value="Upload">
</form
如果您不想使用必需的属性,也可以通过javascript检查是否给出了内容:
function hasContent() {
let fileValue = document.getElementsByName('example')[0].value;
alert(fileValue !== '' ? "has content" : 'no content');
}
<form enctype="multipart/form-data"method="POST">
<input name="example"type="file">
<input type="button"value="Upload"onclick="hasContent();">
</form>
答案 1 :(得分:0)
提交后,您可以在您的php文件中使用此代码:
if($_FILES['example']['tmp_name'] != null){
//Actions you needed
}
如果返回true,则表示已选择文件。