作者:瑶2012瑶_881 | 来源:互联网 | 2023-07-31 19:40
先看效果图:
下面开始说代码
文件上传部分:
<link href&#61;"/static/css/fileinput.css" media&#61;"all" rel&#61;"stylesheet" type&#61;"text/css" />
<script src&#61;"/static/js/canvas-to-blob.min.js" type&#61;"text/Javascript">script>
<script src&#61;"/static/js/sortable.min.js" type&#61;"text/Javascript">script>
<script src&#61;"/static/js/purify.min.js" type&#61;"text/Javascript">script>
<script src&#61;"/static/js/fileinput.js">script>
<script src&#61;"/static/js/zh.js">script>
<script src&#61;"/static/js/pt-BR.js">script>
<script src&#61;"/static/js/theme.js">script>
<script src&#61;"/static/js/LANG.js">script>
<script type&#61;"application/Javascript">function initFileInput(ctrlName, uploadUrl) {var control &#61; $(&#39;#&#39; &#43; ctrlName);control.fileinput({language: &#39;zh&#39;, uploadUrl: uploadUrl, allowedFileExtensions : [&#39;pdf&#39;],showRemove: false,showZoom: false,showCaption: false,browseClass: "btn btn-primary", previewFileIconSettings: {&#39;pdf&#39;: &#39;&#39;}});}
script><div style&#61;"width:50%; padding-top: 5%"><label class&#61;"control-label">Select Filelabel
<input id&#61;"file-Portrait" type&#61;"file" class&#61;"file" data-preview-file-type&#61;"text"><script>initFileInput("file-Portrait", "/api/upload");script>
div>
UPLOAD_FOLDER &#61; &#39;./static/doc&#39;
app.config[&#39;UPLOAD_FOLDER&#39;] &#61; UPLOAD_FOLDER &#64;app.route("/api/upload", methods&#61;["GET", "POST"])
def upload():file &#61; request.files.get("file_data")msg &#61; api_upload(app, file)upload_msg &#61; json.loads(msg.data.decode("utf-8"))errmsg &#61; upload_msg.get("errmsg")return jsonify({"msg": errmsg})def api_upload(app_boj, file):basedir &#61; os.path.abspath(os.path.dirname(__file__)) file_dir &#61; os.path.join(basedir, app_boj.config[&#39;UPLOAD_FOLDER&#39;]) if not os.path.exists(file_dir):os.makedirs(file_dir) fname &#61; file.filenameext &#61; fname.rsplit(&#39;.&#39;, 1)[1] unix_time &#61; int(time.time())new_filename &#61; str(unix_time)&#43;&#39;.&#39;&#43;ext file.save(os.path.join(file_dir, new_filename)) return jsonify({"result": 1, "new_name": new_filename, "errmsg": "上传成功"})
在线查看部分
先看一下这里要用到的pdf.js的组织结构&#xff08;这个很重要&#xff09;
<div class&#61;"container"><div class&#61;"row"><div class&#61;"col-lg-9 col-lg-offset-2" style&#61;"height: 595px"><iframe class&#61;"frame_style" src&#61;"http://127.0.0.1:5000/static/pdfjs/web/viewer.html?file&#61;\static\doc\1481953691.pdf">iframe>div>div>
div>
&#64;app.route(&#39;/show&#39;, methods&#61;["GET"])
def show_test():return render_template("show.html")
按照前面的组织结构组织好pdf.js之后&#xff0c;重点就在iframe的src部分了。这里为了方便演示写死的&#xff0c;可以作为参数传入&#xff0c;就能够实现点击文档在线查看了。
最后放上这个demo的git地址&#xff0c;可以下载pdf.js的部分&#xff0c;嵌入任何语言都一样使用。
[demo地址]