如何将python api请求和响应与javascript集成

时间:2018-11-27 16:32:02

标签: javascript python html api file-upload

我在server.py中有一组api,分别用于文件上传,预处理数据以进行分析等。我想通过UI集成并进行api调用。即使无法上传文件,也无法启动,因为我无法通过UI与API进行交互。请帮助我理解如何将UI与API集成在一起。

API返回JSON文件中的输出:

代码段server.py:

from flask import Flask, render_template, request
from flask_restplus import Resource, Api, fields, reqparse
import os
import pandas
import json
from werkzeug.contrib.fixers import ProxyFix
from waitress import serve
from werkzeug.datastructures import FileStorage
import parser
import uuid
import importlib
@app.route('/dashboard')
def dashboard():
return render_template('dashboard.html')
@api.route('/api/v1/fileupload')
class upload_file(Resource):
@api.expect(file_upload_model)
def post(self):
    try:
        requestid = uuid.uuid4().hex
        parser = reqparse.RequestParser()
        parser.add_argument('file', type=FileStorage, location='files', 
        required=True)
        args = parser.parse_args()
        # checking if the file is present or not.
        #if 'file' not in request.files:
        #    return "No file found"
        file = args.get('file')

        #file = request.files['file']

        path = os.path.join(os.path.join(server_path, requestid + "\\" + 
        "rawdata"))
        if os.path.exists(path):
            pass
        else:
            os.makedirs(path)

        abs_path = path + "\\" + file.filename
        file.save(abs_path)
        return {"requestid": requestid, "upload_status": "success", 
        "location": abs_path}, 200
        except Exception as e:
        requestid = None
        return {"requestid": requestid, "upload_status": "failed::" + str(e) 
        , "location": ""}

dashboard.html的代码段

<form class="navbar-brand" method="POST">
    <script type="text/javascript" language="javascript">
        function checkfile(sender) {
            var validExts = new Array(".csv");
            var fileExt = sender.value;
            fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
            if (validExts.indexOf(fileExt) < 0) {
                alert("Invalid file selected, please select only" +
                    validExts.toString() +"file");
                return false;
            }
            else return true;
        }
    </script>
    <div>Select a file to Upload: <br>
        <input type="file" name="fileupload"
               value="fileupload" id="fileupload" onchange=checkfile(this) /> <br>
        <small>please select .csv file only</small>
    </div>
</form>

1 个答案:

答案 0 :(得分:1)

您似乎丢失了上传文件的整个部分。这段代码应该可以帮助您。

  • 删除了checkfile函数,并使用了accept属性
  • 为表单提交和上传添加了事件监听器
  • 防止页面重定向,您可以决定显示什么
  • output div将显示上传状态。

解决方案

var form = document.forms.namedItem("upload-form");

form.addEventListener('submit', function(e) {
  var output = document.getElementById("output");
  var data = new FormData(this);
  var request = new XMLHttpRequest();

  request.open("POST", "/api/v1/fileupload", true);
  request.onload = function(e) {
    if (request.status == 200) {
      output.innerHTML = "Uploaded!";
    } else {
      output.innerHTML = "Error " + request.status + " occurred when trying to upload your file.<br \/>";
    }
  };

  request.send(data);
  e.preventDefault();
}, false);
<form class="navbar-brand" name="upload-form" enctype="multipart/form-data">
  <div>Select a file to Upload: <br>
      <input
        type="file"
        name="fileupload"
        id="fileupload"
        accept=".csv"
      /> <br>
      <small>please select .csv file only</small>
  </div>
  <button type="submit">Upload</button>
</form>
<div id="output"></div>