下面是關於文件上傳的代碼片段。使用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,我不能上傳文件。
@davidism您好,我修復縮進和結果給了我錯誤的請求 瀏覽器(或代理)發送了一個請求,表明此服務器無法理解。 – thinkmind 2014-08-29 03:28:48
什麼是「CutOffListTemp.id」?具體而言,它是關鍵字還是特定於此應用程序? – 2015-03-10 22:47:13
@thinkmind:我收到了錯誤的請求,瀏覽器發送了一個請求,表示這臺服務器無法理解。你是如何解決這個問題的? – ngunha02 2017-03-16 02:20:20