从 HTML5 拖动和传递上传文件的路径拖放到输入字段

2023-02-24前端开发问题
1

本文介绍了从 HTML5 拖动和传递上传文件的路径拖放到输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在开发一个允许用户上传图像的应用程序(在 Node.js 中,与本例无关).使用带有输入 (type="file") 字段的表单可以正常工作.

I'm working on an application (in Node.js, which is irrelevant for this case) which allows the user to upload an image. It works fine using a form with an input (type="file") field.

但是,我想要的是能够使用 HTML5 拖放来上传图像.据我所知,可以将图像拖动到客户端,并且图像缩略图显示在 div 中.但是,我确实需要一些帮助才能使文件上传正常工作.

However, what I want is to be able to upload an image using HTML5 drag and drop instead. As far as i've come it's possible to drag an image to the client, and the image thumbnail is displayed in a div. However I really need some help with getting the file upload working.

问题是我想使用我现在正在使用的表单,并且(以某种方式)将文件的路径传递给输入字段,即流程将完全像现在一样工作,但不是选择一个通过浏览文件我想通过拖放将其附加到输入字段.

The thing is that I want to use the form that i'm using right now, and (somehow) pass the file's path to the input field, i.e. the flow will work exactly as it do now, but instead of choosing a file by browsing it I want to attach it to the input field by drag and drop.

在下面用于拖放的 js 代码中,拖放到客户端的文件存储在变量file"中,我可以使用file.name"、file.type"和file.size" 与之前使用表单的方式完全相同.但是,我无法访问文件路径"(file.path),这使得无法访问文件服务器端进行上传,就像我之前那样.

In the js code below for drag and drop the file that was dragged to the client is stored in the variable "file", and i'm able to use "file.name", "file.type" and "file.size" exactly the same way as it works since before with the form. However, I can't access the files "path" (file.path) which makes it impossible to access the file server side for uploading the same way as I do it since before.

问题是,是否可以在文件被拖到客户端后将文件对象传递给输入字段,以便我可以点击提交"并上传文件?如果是这样,如何做到这一点?

The question is, is it possible to pass the file object to the input field after the file has been dragged to the client, so that I can click on "submit" and upload the file? If so, how could this be done?

提前致谢!

Dropbox 以及我用于文件上传的表单:

the dropbox as well as the form i'm using for file uploads:

<div id='upload'>
    <article>
        <div id='holder'>
            <p id='status'>File API and FileReader API not supported</p>
        </div>
    </article> 

    <form method='post' enctype='multipart/form-data' action='/file-upload'>
        <p>
            <input type='file' name='thumbnail'>
        </p>
        <p>
            <input type='submit'>
        </p>
    </form>
</div>

拖放代码:

uploadImage: function(){
    var holder = document.getElementById('holder'),
        state = document.getElementById('status');

    if (typeof window.FileReader === 'undefined') {
      state.className = 'fail';
    } else {
      state.className = 'success';
      state.innerHTML = 'File API & FileReader available';
    }

    holder.ondragover = function () { this.className = 'hover'; return false; };

    holder.ondragend = function () { this.className = ''; return false; };

    holder.ondrop = function (e) {
      this.className = '';
      e.preventDefault();

      var file = e.dataTransfer.files[0],
          reader = new FileReader();

      reader.onload = function (event) {
        holder.style.background = 'url(' + event.target.result + ') no-repeat center';
      };

      reader.readAsDataURL(file);

      return false;
    };
},

推荐答案

不能使用文件输入添加文件数据.不过,您可以做的(在其他技术中)是使用 base64(在使用 readAsDataURL 方法时,可以通过 reader.onload 事件作为 event.target.result 本地获得)) 编码数据并将其放入隐藏字段:

You cannot use the file input to add the file data. Nevertheless, what you can do (among other technics) is to use the base64 (natively available through the reader.onload event as event.target.result, when using readAsDataURL method) encoded data and put it into an hidden field :

html

<article>
    <div id='holder'>
        <p id='status'>File API and FileReader API not supported</p>
    </div>
</article> 

<form method='post' enctype='multipart/form-data' action='/file-upload'>
        <input type='file' name='thumbnail' />
        <input type='hidden' name='base64data' />
        <input type='submit' formenctype='application/x-www-form-urlencoded' />
</form>

js

reader = new FileReader();
reader.onload = function (event) {
    document.getElementById('base64data').setAttribute('value', event.target.result);
};
reader.readAsDataURL(file);

从服务器端,您将能够从文件中获取 base64 编码数据,只需对其进行解码并根据需要使用它.

From the server side you'll be able to get the base64 encoded data from the file, just decode it and use it as you want.

在提交表单时,您还可以更改enctype"属性(通过 formenctype 属性完成)并删除基本的 html 文件输入,因为数据将发布在文本字段中.

While submitting the form, you could also change the "enctype" attribute (done through the formenctype attribute) and remove the basic html file input, since the data will be post in a text field.

这篇关于从 HTML5 拖动和传递上传文件的路径拖放到输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Fatal error: Call to a member function fetch_assoc() on a no
业务场景:使用update语句去更新数据库字段。 原因:update接收值不正确。原来代码: $query = "UPDATE student SET date = now() WHERE id = $id";$result = $mysqli-query($query2) or die($mysqli-error); // 问题出现了在这句 $data = $result-fetch_ass...
2024-12-13 前端开发问题
136

layui实现laydate日历控件控制之前日期不可选择
具体实现代码如下: laydate.render({ elem: '#start_time', min:0, //,type: 'date' //默认,可不填}); 只要加一个min参数,就可以控制了。0表示之前的日期不可...
2024-11-29 前端开发问题
133

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 实现实时刷新一个外部的div
主页面上显示了一个合计,在删除和增加的时候需要更改这个总套数的值: //html代码div class="layui-inline layui-show-xs-block" style="margin-left: 10px" id="sumDiv"spanSOP合计:/spanspan${totalNum}/spanspan套/span/div 于是在我们删除这个条数据后,...
2024-11-14 前端开发问题
156

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313