Passing path to uploaded file from HTML5 drag & drop to input field

前端 未结 3 1054
死守一世寂寞
死守一世寂寞 2020-12-29 09:36

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=\"fil

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 10:20

    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

    File API and FileReader API not supported

    js

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

    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.

    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.

提交回复
热议问题