在上传到服务器之前预览.doc/.docx/.pdf文件

Preview .doc/.docx/.pdf files before uploading to server

本文关键字:doc docx 文件 pdf 服务器      更新时间:2023-09-26

我正在使用HTML5 File API上传一些文档(.doc/.docx/.pdf)。我想在上传到服务器之前显示该文档的预览。有没有办法在客户端做这样的事情?

附言:谷歌文档查看器不好,因为它要求文档可以从互联网上访问。

我尝试创建一个小示例,在上传PDF文件之前显示PDF预览。

<!DOCTYPE html>
  <html lang="en">
    <head>
        <title>JavaScript PDF Viewer Demo</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            function PreviewImage() {
                pdffile=document.getElementById("uploadPDF").files[0];
                pdffile_url=URL.createObjectURL(pdffile);
                $('#viewer').attr('src',pdffile_url);
            }
        </script>
    </head>
    <body>
        <input id="uploadPDF" type="file" name="myPDF"/>&nbsp;
        <input type="button" value="Preview" onclick="PreviewImage();" />
        <div style="clear:both">
           <iframe id="viewer" frameborder="0" scrolling="no" width="400" height="600"></iframe>
        </div>
    </body> 
</html>

不确定是否还有人检查这个线程,但我想我会分享我所做的。直接显示预览是不可能的,但您可以创建所选文件的blob对象。类似这样的东西(jQuery):

$('#input').change(function (event) {
    var file = URL.createObjectURL(event.target.files[0]);
    $('element').append('<a href="' + file + '" target="_blank">' + event.target.files[0].name + '</a>');
});

此链接将打开一个新的浏览器选项卡,并显示/下载文件。这不是很漂亮,但很管用。以下是一个示例:https://jsfiddle.net/j9gw023b/3/

否。这是不可能的。

您希望浏览器查看不应该查看的数据文件。您有Office或PDF查看器(好的,当然,PDF组件现在可以在浏览器中使用…)来查看您的数据文件。

如果你想在浏览器中显示预览,你必须先上传并将其存储在"for preview"目录或其他目录中。确定后,将其移动到最终目的地,否则,删除。

File API允许您从文件中读取数据,但随后您在解析和呈现文件时遇到了麻烦。Mozilla已经发布了JavaScript PDF查看器,但我不知道MS Office文件的任何功能。

在过去,你可以做这样的事情:

<object data="word.doc">You do not have Word installed on your machine</object>

不确定这是否仍然支持,但如果支持,您可以使用JS将该对象注入到页面上进行预览。

Ajax上传您的文件,然后上传后返回路径名并预览。

blueimp的jQuery文件上传对我来说很棒。

你可以查看它的基本插件。

https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin

你可以用pdf来做,下面是教程:

https://usefulangle.com/post/87/javascript-preview-pdf-during-upload

不知道doc/docx 是否可行

您可以使用此web组件:https://avipunes.github.io/file-viewer/

这个web组件使用了一些microsoft嵌入端点:https://view.officeapps.live.com/op/embed.aspx?src=${fileURI}

您可以在这里看到一个示例:https://view.officeapps.live.com/op/embed.aspx?src=https://file-examples-com.github.io/uploads/2017/02/file_example_XLS_10.XLS