2014-08-29 166 views
3

下面是關於文件上傳的代碼片段。使用AngularJS上傳文件失敗

這裏是我的HTML代碼,我會選擇和上傳的文件:

<form ng-click="addImportFile()" enctype="multipart/form-data"> 
    <label for="importfile">Import Time Events File:</label><br><br> 
    <label for="select_import_file">SELECT FILE:</label><br> 
    <input id="import_file" type="file" class="file btn btn-default" ng-disabled="CutOffListTemp.id== Null" data-show-preview="false"> 
    <input class="btn btn-primary" type="submit" name="submit" value="Upload" ng-disabled="CutOffListTemp.id== Null"/><br/><br/> 
</form> 

這是我的控制器將鏈接HTML和我的Python文件:

angular.module('hrisWebappApp').controller('ImportPayrollCtrl', function ($scope, $state, $stateParams, $http, ngTableParams, $modal, $filter) { 
    $scope.addImportFile = function() { 
    $http.post('http://127.0.0.1:5000/api/v1.0/upload_file/' + $scope.CutOffListTemp.id, {}) 
    .success(function(data, status, headers, config) { 
     console.log(data); 

     if (data.success) { 
     console.log('import success!'); 
     } else { 
     console.log('importing of file failed'); 
     } 
    }) 
    .error(function(data, status, headers, config) {}); 
}; 

這是我的Python文件:

@api.route('/upload_file/<int:id>', methods=['GET','POST']) 
@cross_origin(headers=['Content-Type']) 
def upload_file(id): 
    print "hello" 
    try: 
     os.stat('UPLOAD_FOLDER') 
    except: 
     os.mkdir('UPLOAD_FOLDER') 
    file = request.files['file'] 
    print 'filename: ' + file.filename 

    if file and allowed_file(file.filename): 
     print 'allowing file' 
     filename = secure_filename(file.filename) 
     path=(os.path.join(current_app.config['UPLOAD_FOLDER'], filename)) 
     file.save(path) #The end of the line which save the file you uploaded. 
     return redirect(url_for('uploaded_file', 
              filename=filename)) 
    return ''' 
     <!doctype html> 
     <title>Upload new File</title> 
     <h1>Upload new File</h1> 
     <p>opsss it seems you uploaded an invalid filename please use .csv only</p> 

     <form action="" method=post enctype=multipart/form-data> 
      <p><input type=file name=file> 
      <input type=submit value=Upload> 
     </form> 
     ''' 

而在控制檯的結果給了我這個,即使我選擇正確的格式的文件:

<!doctype html> 
<title>Upload new File</title> 
<h1>Upload new File</h1> 
<p>opsss it seems you uploaded an invalid filename please use .csv only</p> 
<form action="" method=post enctype=multipart/form-data> 
<p><input type=file name=file> 
<input type=submit value=Upload> 
</form> 

這不是回到我的HTML,我不能上傳文件。

+0

@davidism您好,我修復縮進和結果給了我錯誤的請求 瀏覽器(或代理)發送了一個請求,表明此服務器無法理解。 – thinkmind 2014-08-29 03:28:48

+0

什麼是「CutOffListTemp.id」?具體而言,它是關鍵字還是特定於此應用程序? – 2015-03-10 22:47:13

+0

@thinkmind:我收到了錯誤的請求,瀏覽器發送了一個請求,表示這臺服務器無法理解。你是如何解決這個問題的? – ngunha02 2017-03-16 02:20:20

回答

2

您好我終於可以上傳文件,我改變角部位,我這個改變:

$scope.addImportFile = function() { 
    var f = document.getElementById('file').files[0]; console.log(f); 
    var formData = new FormData(); 
    formData.append('file', f); 
         $http({method: 'POST', url: 'http://127.0.0.1:5000/api/v1.0/upload_file/' +$scope.CutOffListTemp.id, 
         data: formData, 
         headers: {'Content-Type': undefined}, 
         transformRequest: angular.identity}) 
         .success(function(data, status, headers, config) {console.log(data); 
         if (data.success) { 
          console.log('import success!'); 

         } 
        }) 
        .error(function(data, status, headers, config) { 
        }); 
      // } 
     }; 
1

第一件事是關於發佈請求。如果沒有ng-click =「addImportFile()」,瀏覽器通常會負責序列化表單數據並將其發送到服務器。所以,如果你嘗試:

<form method="put" enctype="multipart/form-data" action="http://127.0.0.1:5000/api/v1.0/upload_file"> 
    <label for="importfile">Import Time Events File:</label><br><br> 
    <label for="select_import_file">SELECT FILE:</label><br> 
    <input id="import_file" type="file" name="file" class="file btn btn-default" ng-disabled="CutOffListTemp.id== Null" data-show-preview="false"> 
    <input class="btn btn-primary" type="submit" name="submit" value="Upload" ng-disabled="CutOffListTemp.id== Null"/><br/><br/> 
</form> 

,然後在蟒蛇,讓你的請求URL獨立scope.CutOffListTemp.id的: @ api.route( '/ upload_file',方法= [ 'GET', 'POST' ])

它可能會工作。

或者,如果您想使用自定義函數發送發佈請求,瀏覽器將不再處理序列化內容,您需要自行完成。

在角度上,$ http.post的API是: $ http.post('/ someUrl',data).success(successCallback); 如果我們對數據參數使用「{}」,表示爲空,服務器將不會找到名爲「file」(file = request.files ['file'])的數據。因此,你會看到錯誤的請求

爲了解決這個問題,我們需要使用FORMDATA使這需要你的瀏覽器文件上傳支持HTML5:

$scope.addImportFile = function() { 
    var f = document.getElementById('file').files[0] 
    var fd = new FormData(); 
    fd.append("file", f); 

    $http.post('http://127.0.0.1:5000/api/v1.0/upload_file/'+$scope.CutOffListTemp.id, 
       fd, 
       headers: {'Content-Type': undefined}) 
    .success...... 

除了使用原生以上的JavaScript代碼中,有很多偉大的角上傳文件庫,它可以使文件上傳的角度更容易,你可能會想看看他們中的一個(參考:File Upload using AngularJS):

+0

我試過這個,但仍然出現錯誤。在分析它時,文件本身在請求服務器時沒有保存。 AngularJs或HTMLL上的錯誤?謝謝。 – thinkmind 2014-08-30 01:08:19

+0

謝謝@辛增! :) – thinkmind 2014-08-30 06:41:08