1

I'm getting crazy about this: I have an input file, and through js and I get the content. Now, I need to store it in mysql blob, and then I need to use php to output or save the file (which, for knowing, is a pdf or a jpg).

The problem is that I get a blank file or a corrupted one! I've tried all of the FileReader method, without success: readAsDataURL gives me a corrupted, readAsBinaryString an empty... how can I achieve this?

My code so far for JS:

reader.onload = function(evt) {
        if(evt.target.readyState != 2) return;
        if(evt.target.error) {
            alert('Error while reading file');
            return;
        }
        filecontent = evt.target.result;
        $.ajax({
            url: 'xxx',
            type: "POST",
            data: {
                visura:filecontent,
                visura_nome:$("#visura").get(0).files[0].name
            },
            ajax: false,
            scriptCharset: "utf-8",
            contentType: "application/x-www-form-urlencoded; charset=UTF-8"
        }).done(function (response) {
            ...
            return false;
        });
        return false;
    };
    reader.readAsBinaryString($("#visura").get(0).files[0]);

For PHP:

$file=$row["visura"];
$visura_nome=explode(".",$row["visura_nome"]);
$visura_nome=$visura_nome[count($visura_nome)-1];
if($visura_nome=="pdf"){
    header("Content-type:application/pdf");
    header("Content-Disposition:attachment;filename=visura.pdf");
    header("Content-Disposition:filename=visura.pdf");
}else{
    header("Content-type:image/".$visura_nome);
    header("Content-
Disposition:attachment;filename=visura.".$visura_nome);
    header("Content-Disposition:filename=visura.".$visura_nome);
}
echo $file;
Zak
  • 531
  • 2
  • 14
  • 37
  • 1
    You are sending the ``Content-Disposition`` header twice. Try sending ``inline`` so that it doesn't force a download, also quoting the filename is a good idea. Try sending this single header after the ``Content-type``, something like this ``header('Content-Disposition:inline;filename="'. $visura_nome .'"');``. Also, try changing ``Content-type`` to ``Content-Type`` as [some browsers implementation do not treat the http header fields case-insensitive as they should](https://stackoverflow.com/a/34039108/5873008). Hope this helps. – alistaircol May 24 '17 at 05:29
  • Also, [readfile](http://php.net/manual/en/function.readfile.php) would be better in this case over ``echo``. – alistaircol May 24 '17 at 05:33
  • thanks @alistaircol !!! – Zak May 24 '17 at 07:32
  • readAsBinaryString doesn't do what you think, JS strings cannot represent arbitrary binary data. Also [readAsBinaryString](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString#Specifications) is deprecated and removed from the FileAPI spec. – Musa Jun 16 '17 at 18:26

0 Answers0