使用ng-file-upload上传文件并将其发送给Flask

时间:2016-10-03 21:48:21

标签: python angularjs flask

我正在尝试在我的Flask应用中使用ng-file-upload,但我很难将其发送到Flask main.py进行保存。我本可以使用烧瓶url_for()做一个简单的提交,但我想将Flask放在后端,AngularJS放在前端。

此外,我想使用此角度插件中的拖放字段功能而不是上传文件按钮,但我认为这是我的问题所在。我不认为烧瓶是从request.files认出来的。我不确定我是否正确打电话,或者可能只是一个简单的解决方案而且我没有看到它。

Flask main.py

@app.route("/", methods = ['GET', 'POST'])
def index():

if request.method == 'POST':
    print 'unknown went through'
    filestorage = request.files['user_file']
    print filestorage
    if not filestorage:
        return jsonify(fileStatus = False)

    if filestorage.filename.endswith('.xlsx'):
        print "you uploaded a excel file"
        file_new_name = 'dataexcel.xlsx'
        file_type = 'excel'

    elif filestorage.filename.endswith('.csv'):
        print "you uploaded a csv file"
        file_new_name = 'datacsv.csv'
        file_type = 'csv'

    path = "static/uploads/" + file_new_name


    if os.path.exists(path):
        print 'i exist'
        os.remove(path)
        filename = docs.save(filestorage, None, file_new_name)

    else:
        print "i don't exist"
        filename = docs.save(filestorage, None, file_new_name)


    session['path'] = path
    session['file_type'] = file_type

    return jsonify(fileStatus = True)

我知道" POST"是有效的,因为我可以看到来自此打印语句print 'unknown went through'的消息,之后它无法识别filestorage变量

这是我的角度控制器:

myApp.controller('UploadFileCtrl',[
'$scope',
'$http',
'Upload',
 function($scope, $http, Upload){



// upload later on form submit or something similar
$scope.submit = function(files) {
  if ($scope.files) {
    $scope.upload($scope.files);
  }
}

// upload on file select or drop
$scope.upload = function (files) {
  console.log('it was uploaded');
    Upload.upload({
        url: '/',
        method: 'POST',
        data: {file: files}

    }).then(function (resp) {
        // console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
        console.log(resp.data);
    }, function (resp) {
        console.log('Error status: ' + resp.status);
        console.log(resp);
    }, function (evt) {
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
    });
}

}])

html表格:

<form ng-click="submit(files)">
<div ngf-drop ngf-select ng-model="files" class="drop-box"
    ngf-drag-over-class="'dragover'" ngf-multiple="true" ngf-allow-dir="true"
  name="user_file" type="file">Drop pdfs or images here or click to upload</div>
<div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>

<button type="submit">submit</button>

我仍然不熟悉Flask,但它是一个很酷的web框架,将它与AngularJS集成将非常棒。我们将非常感谢您的帮助!

更新

我实际上是要在Flask中上传,我需要它用filestorage = request.files['user_file']替换filestorage = request.files['file']。就像我说的那样,Flask没有通过html中提供的名称来识别它,我不知道为什么。我没能在上面的main.py中提供这一行return render_template('index.html')。由于Flask不再存在于html中,这可能是Flask无法识别表单中name的原因吗?

修订了main.py

@app.route("/", methods = ['GET', 'POST'])
def index():

if request.method == 'POST':
  print 'unknown went through'
  filestorage = request.files['file']
  print filestorage
  if not filestorage:
    return jsonify(fileStatus = False)

  if filestorage.filename.endswith('.xlsx'):
    print "you uploaded a excel file"
    file_new_name = 'dataexcel.xlsx'
    file_type = 'excel'

  elif filestorage.filename.endswith('.csv'):
    print "you uploaded a csv file"
    file_new_name = 'datacsv.csv'
    file_type = 'csv'

  path = "static/uploads/" + file_new_name


  if os.path.exists(path):
    print 'i exist'
    os.remove(path)
    filename = docs.save(filestorage, None, file_new_name)

  else:
    print "i don't exist"
    filename = docs.save(filestorage, None, file_new_name)


  session['path'] = path
  session['file_type'] = file_type

  return jsonify(fileStatus = True)
return render_template('index.html')

此外,我必须在html中将ngf-multiple更改为false,这是发送一个数组,因此Flask期待一个字典。

修改了html:

<form ng-click="submit(files)">
<div ngf-drop ngf-select ng-model="files" class="drop-box"
ngf-drag-over-class="'dragover'" ngf-multiple="true" ngf-allow-dir="true" name="user_file" type="file">Drop pdfs or images here or click to upload</div>
<div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>

<button type="submit">submit</button>

0 个答案:

没有答案