简体   繁体   中英

Is there a way of getting an image file contents without submitting a form in html/php?

I'm trying to send an image file to MySQL (mediumblob). I can get the contents of a file easily using file_get_contents($image) and easily send this to MySQL however, the server I am using does not allow me to submit any uploaded file and therefore cannot get the file contents at all.

Is there a way of just selecting the file, placing it into a variable without submitting the form? Thanks in advance.

If interpret Question correctly, try utilizing event.preventDefault()

 var _files = []; $("form").on("change", function(event) { event.preventDefault(); _files.push(e.target.files[0]); console.log(_files); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <form method="POST" action="/abc"> <input type="file" accepts="image/*" /> </form> 

Its a pity you cant upload files. However there are several ideas you can try. This is one of them:

  1. Read file using javascript. fiddle here: https://jsfiddle.net/d5mg66uw/
  2. Upload the file as string using ajax call
  3. Save the file on the server

You can easily read file from your computer with javascript like this:

function readSingleFile(evt) {
    var f = evt.target.files[0];

    if (f) {
        var r = new FileReader();
        r.onload = function (e) {
            var contents = e.target.result;
            alert("Got the file.n" + "name: " + f.name + "n" + "type: " + f.type + "n" + "size: " + f.size + " bytesn" + "starts with: " + contents.substr(1, contents.indexOf("n")));
        }
        r.readAsText(f);
    } else {
        alert("Failed to load file");
    }
}

document.getElementById('fileinput').addEventListener('change', readSingleFile, false);

the file content will be in the contents variable

Then just upload it using

$.post('fileuploading.php', {filecontents: contents})

and you are done. Either input it to database or save it as an image. What an elegant solution.

FIY: this could get hairy on older browsers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM