14

So in my application, users have the option to upload a file to an <input type = "file" id = "my-file"> (HTML 5 File input). I can subsequently grab this file using the following Javascript:

var files = $("#my-file").files;
var file = files[0];

Can I somehow use this var file as the data in an <object> tag? Here is an example of an object tag where the PDF is grabbed by hitting a URL and contacting the server.

<object data="data/test.pdf" /*<-- I want the var file here */ type="application/pdf" width="300" height="200">
</object>

How can I accomplish this? Please note, I must support Internet Explorer 11.

UPDATE:

I've tried something that ultimately ended in failure. I converted the PDF to a data-uri using FileReader and then used that in the data attribute of the <object> tag, which renders perfectly in Chrome but not at all in Internet explorer.

var files = $(e.currentTarget.files);
file = files[0];
var reader = new FileReader();
reader.onloadend = function() {
    var data = reader.result;
    console.log(data);
    $("#content").prepend('<object id="objPdf" data="'+data+'" type="application/pdf"></object>');
};
reader.readAsDataURL(file);

Where the reader data comes out looking like:

data:application/pdf;base64,JVBERi0xLjQKJe...

Here is the reason PDF's don't work with this approach in Internet Explorer (images only)...so sad :(

UPDATE 2:

Tried pdf.js with some success...it displays the PDF on the page, although it is incredibly slow (5 seconds for a single page) in Internet Explorer 11. It also only displays one page at a time, whereas the <object> tag displayed all pages instantly in a nice scrollable container. While this is an extreme fallback option, I'd like to not go down this route.

Anyone have any other idea as to how I can preview the PDF's that the user uploads directly in the webpage?


I would try this insetad of simply stop(); this line

setOnFinished(e->tryToStop());

And create this method as:

public void tryToStop(){
    if(!started)
        fm.stop();
}

stopProcess() method changes the started variable, so it will stop in this two cases:

  1. if it is finished

AND

  1. if it is reqested to stop

Not tested, just an idea

4

1 に答える 1

4

はい、ファイルで動作するようになりました...

HTML:

<object id="pdf" data="" type="application/pdf"></object>

Javascript (Jクエリ)

var fr = new FileReader();
fr.onload = function(evtLoaded) {
  $('#pdf').attr('data', evtLoaded.target.result );
};
fr.readAsDataURL(inFile);

あなたのアプローチと比較して、イベントを使用して「ファイルの読み取りが完了しました」コールバックを別の方法で使用します。私が正しければ、読み取りが成功したか失敗したかに関係なく、「loadend」は常に呼び出されます。

2021 年 8 月 4 日の付録:
@Adil が複数の PDF について語っています。まあ、この解決策は1について話します.私はいくつかのPDFを試したことはありません. ソリューションは html の「id」によって作成されるため、「id」にはページごとにシングルトン パターンが付属していることがわかります。それにもかかわらず、作成するユースケースが何であれ、ページごとに数個の PDF で何とか実行できると確信しています。

@netotz ここでは調査しませんでした。ハードウェアに関する問題が発生する可能性があると思います。それが発生するブラウザやオペレーティングシステムの内部については言及していません...私は(間違っている可能性がありますが)1.8 MBはかなり少量のデータであると推測しています...

于 2016-12-15T12:56:15.070 に答える