精华内容
下载资源
问答
  • 转自: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example.3A_Using_object_URLs_to_display_images ...Using the File API, which was added to the DOM in HTML5, it's now

    转自: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example.3A_Using_object_URLs_to_display_images


    Using the File API, which was added to the DOM in HTML5, it's now possible for web content to ask the user to select local files and then read the contents of those files. This selection can be done by either using an HTML <input> element or by drag and drop.

    If you want to use the DOM File API from extensions or other browser chrome code, you can; however, note there are some additional features to be aware of. See Using the DOM File API in chrome code for details.

    Accessing selected file(s)

    Consider this HTML:

    <input type="file" id="input">

    The File API makes it possible to access a FileList containing File objects representing the files selected by the user.

    If the user selects just one file, it is then only necessary to consider the first file of the list.

    Accessing one selected file using a classical DOM selector:

    var selectedFile = document.getElementById('input').files[0];

    Accessing selected file(s) on a change event

    It is also possible (but not mandatory) to access the FileList through the change event:

    <input type="file" id="input" onchange="handleFiles(this.files)">

    When the user selects a file, the handleFiles() function gets called with a FileList object containing File objects representing the files selected by the user.

    If you want to let the user select multiple files, simply use the multiple attribute on the input element:

    <input type="file" id="input" multiple onchange="handleFiles(this.files)">

    In this case, the file list passed to the handleFiles() function contains one File object for each file the user selected.

    Dynamically adding a change listener

    You need to use EventTarget.addEventListener() to add the change event listener, like this:

    var inputElement = document.getElementById("input");
    inputElement.addEventListener("change", handleFiles, false);
    function handleFiles() {
      var fileList = this.files; /* now you can work with the file list */
    }

    Note that in this case, the handleFiles() function itself is the event handler, unlike previous examples where it was called by an event handler which passed it a parameter.

    Getting information about selected file(s)

    The FileList object provided by the DOM lists all of the files selected by the user, each specified as a File object. You can determine how many files the user selected by checking the value of the file list's length attribute:

    var numFiles = files.length;

    Individual File objects can be retrieved by simply accessing the list as an array:

    for (var i = 0, numFiles = files.length; i < numFiles; i++) {
      var file = files[i];
      ..
    }

    This loop iterates over all the files in the file list.

    There are three attributes provided by the File object that contain useful information about the file.

    name
    The file's name as a read-only string. This is just the file name, and does not include any path information.
    size
    The size of the file in bytes as a read-only 64-bit integer.
    type
    The MIME type of the file as a read-only string or "" if the type couldn't be determined.

    Example: Showing file(s) size

    The following example shows a possible use of the size property:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>File(s) size</title>
    <script>
    function updateSize() {
      var nBytes = 0,
          oFiles = document.getElementById("uploadInput").files,
          nFiles = oFiles.length;
      for (var nFileId = 0; nFileId < nFiles; nFileId++) {
        nBytes += oFiles[nFileId].size;
      }
      var sOutput = nBytes + " bytes";
      // optional code for multiples approximation
      for (var aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
        sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
      }
      // end of optional code
      document.getElementById("fileNum").innerHTML = nFiles;
      document.getElementById("fileSize").innerHTML = sOutput;
    }
    </script>
    </head>
    
    <body onload="updateSize();">
    <form name="uploadForm">
    <p><input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple> selected files: <span id="fileNum">0</span>; total size: <span id="fileSize">0</span></p>
    <p><input type="submit" value="Send file"></p>
    </form>
    </body>
    </html>

    Using hidden file input elements using the click() method

    Starting in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1), you can hide the admittedly ugly file <input> element and present your own interface for opening the file picker and displaying which file or files the user has selected. You can do this by styling the input element with display:none and calling the click() method on the <input> element.

    Consider this HTML:

    <input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
    <a href="#" id="fileSelect">Select some files</a>

    The code that handles the click event can look like this:

    var fileSelect = document.getElementById("fileSelect"),
      fileElem = document.getElementById("fileElem");
    
    fileSelect.addEventListener("click", function (e) {
      if (fileElem) {
        fileElem.click();
      }
      e.preventDefault(); // prevent navigation to "#"
    }, false);

    You can style the new button for opening the file picker as you wish.

    Using a label element to trigger a hidden file input element

    To allow opening the file picker without using JavaScript (the click() method), a <label> element can be used.

    Consider this HTML:

    <input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
    <label for="fileElem">Select some files</label>

    There is no need to add JavaScript code to call fileElem.click(). Also in this case you can style the label element as you wish.

    Selecting files using drag and drop

    You can also let the user drag and drop files into your web application.

    The first step is to establish a drop zone. Exactly what part of your content will accept drops may vary depending on the design of your application, but making an element receive drop events is easy:

    var dropbox;
    
    dropbox = document.getElementById("dropbox");
    dropbox.addEventListener("dragenter", dragenter, false);
    dropbox.addEventListener("dragover", dragover, false);
    dropbox.addEventListener("drop", drop, false);

    In this example, we're turning the element with the ID dropbox into our drop zone. This is done by adding listeners for the dragenter, dragover, and drop events.

    We don't actually need to do anything with the dragenter and dragover events in our case, so these functions are both simple. They just stop propagation of the event and prevent the default action from occurring:

    function dragenter(e) {
      e.stopPropagation();
      e.preventDefault();
    }
    
    function dragover(e) {
      e.stopPropagation();
      e.preventDefault();
    }

    The real magic happens in the drop() function:

    function drop(e) {
      e.stopPropagation();
      e.preventDefault();
    
      var dt = e.dataTransfer;
      var files = dt.files;
    
      handleFiles(files);
    }

    Here, we retrieve the dataTransfer field from the event, pull the file list out of it, and then pass that to handleFiles(). From this point on, handling the files is the same whether the user used the input element or drag and drop.

    Example: Showing thumbnails of user-selected images

    Let's say you're developing the next great photo-sharing website and want to use HTML5 to display thumbnail previews of images before the user actually uploads them. You can establish your input element or drop zone as discussed previously and have them call a function such as the handleFiles() function below.

    function handleFiles(files) {
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var imageType = /^image\//;
        
        if (!imageType.test(file.type)) {
          continue;
        }
        
        var img = document.createElement("img");
        img.classList.add("obj");
        img.file = file;
        preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed.
        
        var reader = new FileReader();
        reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
        reader.readAsDataURL(file);
      }
    }

    Here our loop handling the user-selected files looks at each file's type attribute to see if it's an image file (by doing a regular expression match on the MIME type string pattern "image/*"). For each file that is an image, we create a new img element. CSS can be used to establish any pretty borders or shadows and to specify the size of the image, so that doesn't need to be done here.

    Each image has the CSS class obj added to it, making it easy to find in the DOM tree. We also add a file attribute to each image specifying the File for the image; this will let us fetch the images for actual upload later. We use Node.appendChild() to add the new thumbnail to the preview area of our document.

    Next, we establish the FileReader to handle asynchronously loading the image and attaching it to the img element. After creating the new FileReader object, we set up its onload function and then call readAsDataURL() to start the read operation in the background. When the entire contents of the image file are loaded, they are converted into a data: URL which is passed to the onload callback. Our implementation of this routine sets the img element's src attribute to the loaded image which results in the image appearing in the thumbnail on the user's screen.

    Using object URLs

    Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) introduces support for the DOM window.URL.createObjectURL() and window.URL.revokeObjectURL() methods. These let you create simple URL strings that can be used to reference any data that can be referred to using a DOM File object, including local files on the user's computer.

    When you have a File object you'd like to reference by URL from HTML, you can create an object URL for it like this:

    var objectURL = window.URL.createObjectURL(fileObj);

    The object URL is a string identifying the File object. Each time you call window.URL.createObjectURL(), a unique object URL is created even if you've created an object URL for that file already. Each of these must be released. While they are released automatically when the document is unloaded, if your page uses them dynamically you should release them explicitly by calling window.URL.revokeObjectURL():

    window.URL.revokeObjectURL(objectURL);

    Example: Using object URLs to display images

    This example uses object URLs to display image thumbnails. In addition, it displays other file information including their names and sizes.

    The HTML that presents the interface looks like this:

    <input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
    <a href="#" id="fileSelect">Select some files</a> 
    <div id="fileList">
      <p>No files selected!</p>
    </div>

    This establishes our file <input> element as well as a link that invokes the file picker (since we keep the file input hidden to prevent that less-than-attractive user interface from being displayed). This is explained in the section Using hidden file input elements using the click() method, as is the method that invokes the file picker.

    The handleFiles() method follows:

    window.URL = window.URL || window.webkitURL;
    
    var fileSelect = document.getElementById("fileSelect"),
        fileElem = document.getElementById("fileElem"),
        fileList = document.getElementById("fileList");
    
    fileSelect.addEventListener("click", function (e) {
      if (fileElem) {
        fileElem.click();
      }
      e.preventDefault(); // prevent navigation to "#"
    }, false);
    
    function handleFiles(files) {
      if (!files.length) {
        fileList.innerHTML = "<p>No files selected!</p>";
      } else {
        fileList.innerHTML = "";
        var list = document.createElement("ul");
        fileList.appendChild(list);
        for (var i = 0; i < files.length; i++) {
          var li = document.createElement("li");
          list.appendChild(li);
          
          var img = document.createElement("img");
          img.src = window.URL.createObjectURL(files[i]);
          img.height = 60;
          img.onload = function() {
            window.URL.revokeObjectURL(this.src);
          }
          li.appendChild(img);
          var info = document.createElement("span");
          info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
          li.appendChild(info);
        }
      }
    }

    This starts by fetching the URL of the <div> with the ID fileList. This is the block into which we'll insert our file list, including thumbnails.

    If the FileList object passed to handleFiles() is null, we simply set the inner HTML of the block to display "No files selected!". Otherwise, we start building our file list, as follows:

    1. A new unordered list (<ul>) element is created.
    2. The new list element is inserted into the <div> block by calling its Node.appendChild() method.
    3. For each File in the FileList represented by files:
      1. Create a new list item (<li>) element and insert it into the list.
      2. Create a new image (<img>) element.
      3. Set the image's source to a new object URL representing the file, using window.URL.createObjectURL() to create the blob URL.
      4. Set the image's height to 60 pixels.
      5. Set up the image's load event handler to release the object URL since it's no longer needed once the image has been loaded. This is done by calling the window.URL.revokeObjectURL() method and passing in the object URL string as specified by img.src.
      6. Append the new list item to the list.

    Here is a live demo of the code above:



    展开全文
  • js自动获取input file的文件名称

    千次阅读 2017-12-28 17:01:30
    JS代码: function getfilename(){ var file = $("#fileid").val(); var pos=file.lastIndexOf("\\"); return file.substring(pos+1); 方法二:正则表达式 var strFileName=file.replace(/^.+?\\(

    HTML代码:

    <input type="file" name="file" id="fileid"    οnchange="getfilename();" ></input>

    JS代码:

    <script>
    				function getfilename(){
    					//方法一
    				    var file = $("#fileid").val();
    				    var pos=file.lastIndexOf("\\");
    				    return file.substring(pos+1);
    				  	//方法二:正则表达式
    				    var strFileName=file.replace(/^.+?\\([^\\]+?)(\.[^\.\\]*?)?$/gi,"$1");  //正则表达式获取文件名,不带后缀
    				    var FileExt=file.replace(/.+\./,"");   //正则表达式获取后缀
    				    //方法三
    				    var img = document.getElementById('fileid');
    					var imgName = img.files[0].name;
    				}
    		</script>


    展开全文
  • 关于js自动获取input file的文件名称

    万次阅读 2016-07-14 09:34:18
     onchange="getfilename();" > function getfilename(){ ... var file = $("#fileid").val(); var pos=file.lastIndexOf("\\");  return file.substring(pos+1); 方法二:正则表达式 var strFileNa
    html代码:
        <input type="file" name="file" id="fileid"    οnchange="getfilename();" ></input>
    <script>
    function getfilename(){
       var file = $("#fileid").val();
       var pos=file.lastIndexOf("\\");
        return file.substring(pos+1);  
      方法二:正则表达式
      var strFileName=file.replace(/^.+?\\([^\\]+?)(\.[^\.\\]*?)?$/gi,"$1");  //正则表达式获取文件名,不带后缀
      var FileExt=file.replace(/.+\./,"");   //正则表达式获取后缀
    }
    </script>
    展开全文
  • 获取方式如下所示:弹窗如下:获取成功!! 欢迎各位大佬批评指正

    获取方式如下所示:

    弹窗如下:

    获取成功!!

                                    欢迎各位大佬批评指正

    展开全文
  • 前面我们学习了File获取指定路径下的所有文件或者文件夹的名称,还有获取指定路径下所有的文件对象。这篇,我们分别利用这两个方法来做一个练习题,例如输出桌面文件中所有的png文件名称。1. 文件名称方法如果你桌面...
  • File类的概述和构造方法 A:File类的概述 查看API 文件和目录路径名的抽象表示形式 这个File类可以用来表示文件,也可以用来表示目录 B:构造方法 File(String pathname):根据一个路径得到File对象 File(String parent...
  • 获取input type=file的文件名方法: let filePath = $("input[type = 'file']").val(); //获取路径 let urlArr = filePath.split("\\"); //以反斜杠'\'截取文件名为数组 let fileNam...
  • //formData.append('file', this.files[i]);//上传单个文件的添加方式 if(files.length){ for(var i=0;i;i++){ formData.append('file[]', this.files[i]);//上传多个文件的添加方式 uploadFiles.push(files[i]....
  • 关于android7.0的FileProvider获取File路径

    千次阅读 2018-01-30 14:51:20
    关于FileProvider的使用,网上随便搜索一下,都有一堆使用的教程说明,但这些说明,都只是告诉我们配置FileProvider,使系统认识这个FileProvider. 但是在我的项目中需要的是获取文件的绝对路径,于是就有了这个文章. ...
  • ChannelSftp下载目录下所有或指定文件、ChannelSftp获取某目录下所有文件名称、InputStream转File /** * ChannelSftp下载目录下所有或指定文件 * ChannelSftp获取某目录下所有文件名称 * InputStream转File ...
  • https://blog.csdn.net/sdut406/article/details/85647982
  • php HTML file 获取绝对路径

    千次阅读 2011-06-21 16:06:00
    在php编程中,上传文件的时,往往我们有时候需要获取HTML控件file 的绝对路径,而file 本身的函数只提供了获取文件名称,以及大小,临时路径。以下给出获取绝对路径的详细实现:function chk(){ var fileurl = ...
  • Java中File类-10-File类的的获取功能

    千次阅读 2018-07-08 00:02:19
    主要有获取绝对路径,获取路径,获取名称获取长度,字节数,获取最后一次修改时间,毫秒值,获取指定路径下所有文件或者文件夹的名称的数组,获取指定路径下文件或文件夹的File数组。1.获取绝对路径 在Eclipse...
  • File获取文件的属性

    千次阅读 2017-11-23 21:53:46
    /* * 查询文件的属性: * public String getAbsolutePath():获取绝对路径 * public String getPath():... * public String getName():获取名称 * public long length():获取长度。字节数 * public long lastMo
  • 需求有这样一个需求,需要找出某文件夹下所有文件的名称,进行筛选,找出文件名称中含有某单词的文件。代码 /*** * 查询文件夹下所有文件的名称 */ public static boolean creatConcatTxtFile(){ File f=new File...
  • 1、假如现在需要获取用户上传文件的详细信息,如 文件名称、文件大小、文件类型、上传修改时间等等。 H5 File 对象概述 1、文件上传表单如下所示:method 必须是 post、enctype 必须是multipart/form-data 类型...
  • vue input type=file 获取文件本地路径

    万次阅读 2018-06-02 22:55:29
    file&quot; :id=&quot;id&quot; name=&quot;image&quot; class=&quot;getImgUrl_file&quot; @change=&quot;preview($event)&quot;&amp;gt; srcipt preview(event){ ...
  • File文件的属性获取

    2017-01-20 22:34:13
    给大家介绍一些文件属性的获取... * File类的属性获取 * @author lyl * */ public class FileProperty { public static void main(String[] args) { File file=new File("text.txt"); //判断文件是否存在 System
  • * 获取指定目录下的文件夹和文件的File对象或是字符串名称。 * 也可以通过filter获取指定的文件夹或者指定类型的文件 * 这里面需要做一个总结,如何利用jdk的源码去理解不熟悉的方法的应用。 */ import java.io....
  • jquery input file获取文件名

    千次阅读 2014-09-15 14:41:44
    最近遇到了如下的问题,当用户选择一个文件的时候,将标题自动设置为文件名 参考了很多方法后,最后兼容各个浏览器的代码如下: function getFileName(obj){ var fileName=""; if(typeof(fileName) !...
  • * File 操作系统中的文件(file),文件夹(directory),路径(path)封装成File对象 * File与系统无关的类 */ public static void main(String[] args) { /* * File.pathSeparator;路径分隔符 * windows中...
  • JAVA基础再回首(二十)——File类概述、创建、删除、重命名、判断、获取、文件名称过滤器 版权声明:转载必须注明本文转自程序员杜鹏程的博客:http://blog.csdn.net/m366917 我们要想实现IO的操作,就必须知道硬盘...
  • 可以获取文件的绝对路径,在不同浏览器下,显示存在兼容问题。 在IE下可以获取绝对路径,在火狐浏览器下获取的是文件的名称。 在ie8以下的执行结果: 在火狐浏览器下的执行结果:
  • Java把电脑中的文件和文件夹(目录)封装为了一个File类,我们可以使用File类对文件和文件夹进行操作:创建一个文件/文件夹,删除文件/文件夹,获取文件/文件夹,判断文件/文件夹是否存在,对文件夹进行遍历,获取...
  • <input type="file" name="file" id="file"/> 用var fileName = document.getElementById("file").value;得到file的上传路径,但是在IE8或更高版本的IE中得到的路径是:c:\fakepath\xxx路径,怎么才能得到上传的...
  • input name=file" type="file" id="file"/> Jquery代码:var file;$('#file').change(function(){ file=$(this).val(); }) var arr = file.split('\\');//注split可以用字符或字符串分割 var fileName = arr[arr...
  • 在Windows下的路径分隔符和Linux下的路径分隔符是不一样的,当直接使用绝对路径时,跨平台会暴出“No such file or diretory”的异常。   比如说要在temp目录下建立一个test.txt文件,在Windows下应该这么写: ...
  • File类 Java文件类以抽象的方式代表文件名和目录路径名,定义了一些与平台无关的方法来操作文件,可以通过调用File类中的方法,实现创建、删除、重命名文件等。File对象代表磁盘中实际存在的文件和目录. 构造方法: ...
  • javafile用于获取目录下符合条件的文件集合

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 631,995
精华内容 252,798
关键字:

file的获取名称