我正在尝试创建一个控件,您可以在其中选择要在表单中提交的文件,并将文件放入其中以执行相同的操作.我有这样的东西,如果它是一个图像,它也会显示该文件的预览:
<div class="preview-image-container">
<input type="file" name="File" id="File" accept="image/*"
class="image-url form-control" style="display:none;" />
<div class="preview-image-dummy"></div><img class="preview-image-url" />
<div class="preview-image-instruction">
<div class="preview-image-btn-browse btn btn-primary">Select file</div>
<p>or drop it here.</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
用户删除文件preview-image-container.该文件未随AJAX提交,用户需要提交包含更多数据的表单.
出于安全原因,我们不允许使用JavaScript更改输入文件的值.但是,我知道默认输入文件支持droppable,并且有一些网站让我们通过将它们放在表单中来选择文件,所以我的猜测是有一种方法可以做到这一点.
正如您从MCVE中看到的,我只对使用jQuery或纯JavaScript而不使用其他库感兴趣.
虽然可以使用dropzone.js,但它不符合我的要求,需要花费大量的时间来定制它的外观.此外,dropzone.js具有某些在我的ASP.NET应用程序中无法满足的配置要求.
有一个类似的问题,但没有一个正确的答案:
如何在HTML格式的表单中将文件对象设置为输入文件?
也不像上传拖放图像输入文件和预览,因为我已经实现了拖放和预览操作.我的问题是特定于在父容器中删除文件时输入空文件的问题.
我有一个放置区域,我想检测被拖动的项目是文件夹还是文件.在chrome中我通过使用实现了这一点
for (var i = 0; i < nrOfFiles; i++) {
var entry = e.originalEvent.dataTransfer.items[i].webkitGetAsEntry();
if (entry.isDirectory) {
//folder detection
}
Run Code Online (Sandbox Code Playgroud)
在Firefox中,无法使用上述解决方案(webkit),在花了很多时间试图解决这个问题后,我想出了以下解决方案(并且失败了)
我检查拖动的项目是否没有类型和大小,如下所示,并且在大多数情况下它按预期工作.从我所看到的这个效率并不高,因为有些文件可能没有文件扩展名,所以我尝试用FileReader API读取文件为二进制字符串(readAsBinaryString)或readAsArrayBuffer,并在项目为的情况下捕获异常不可读,但永远不会抛出异常.
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < nrOfFiles; i++) {
if (files[i].size === 0 && files[i].type==="") {
try{
var reader = new FileReader();
reader.readAsBinaryString(files[i]);
}catch(e){
//folder detection ?
}
}}
Run Code Online (Sandbox Code Playgroud)在下面的解决方案中,我正在尝试使用mozGetDataAt,这是相应的webkitGetAsEntry(???不是100%关于这个请纠正我,如果我错了)但我得到一个安全例外.
var entry = e.originalEvent.dataTransfer.mozGetDataAt("application/x-moz-file",i);
if (entry.isDirectory) { //not even reaching this statement. idk if isDirectory is applicable to entry
//folder detection? …Run Code Online (Sandbox Code Playgroud)通过创建一个输入标签,例如:
<input type="file">
Run Code Online (Sandbox Code Playgroud)
用户无法选择目录。通过启用某些标志:
<input type="file" webkitdirectory mozdirectory msdirectory odirectory directory multiple>
Run Code Online (Sandbox Code Playgroud)
用户现在可以选择任何目录,但不能选择单个文件。
有什么办法可以同时启用吗?
I'd like to create a dropdown menu and display all the files currently in a directory so when the user clicks on an item in that list of files, it prints to console the name of that file.
Here is what I've come up with so far:
HTML
<form method="post">
<select name="DropdownList">
<option value="file1">fileArray[0]</option>
<option value="file2">fileArray[1]</option>
<option value="file3">fileArray[2]</option>
<option value="file4">fileArray[3]</option>
</select>
</form>
Run Code Online (Sandbox Code Playgroud)
The problem with doing this hardcoded is what if there are 10 files instead of 4? Trying to …