Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

angularjs - AngularJS + Django文件上传(AngularJS + Django file upload)

I am referring to the official Django documentation https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/ on Handling uploaded files with a model, as well as 'ngFileUpload' and Django Rest Framework on Stack Overflow.

(我指的是官方的Django文档https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/关于使用模型处理上传的文件,以及“ ngFileUpload”和Django Rest Framework on Stack溢出。)

However, I am still unable to upload a file.

(但是,我仍然无法上传文件。)

html:

(的HTML:)

<div id="dropdown-lvl5" class="panel-collapse collapse" ng-submit="UploadFile">
      <div class="panel-body" style="width:198px">
        <input type="file" id="files" name="files[]" multiple size="10" class="inputfile_upload" file="file" files-model="file.file" ng-controller="fileUploadController" accept="application/pdf"/>
        <label for="files"> <span class="glyphicon glyphicon-open"></span>Select a file to upload</label>
       <div>
              <span ng-show="!files.length">No files selected</span>
              <ul>
                  <li ng-repeat="file in files">{{file.file}}</li>
              </ul>
          </div>
      </div>
    </div>

fileUploadController.js:

(fileUploadController.js:)

app.controller('fileUploadController', function($scope, Upload, $timeout){

$scope.Submit = function(file){
   $file.upload = Upload.upload({
  url: '../../file',
  data: {file: file},
  arrayKey: '',
});

file.upload.then(function (response) {
  $timeout(function () {
    file.result = response.data;
  });
}, function (response) {
  if (response.status > 0)
    $scope.errorMsg = response.status + ': ' + response.data;
}
}
});

fileUploadService.js:

(fileUploadService.js:)

app.service('fileUploadService', ['$http', function ($http) {
this.post = function(uploadUrl, data){
    var fd = new FormData();
    fd.append('file', file);
    for(var key in data)
        fd.append(key, data[key]);
    $http.post(uploadUrl,fd, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    })
    }
}
}

}

(})

directive.js:

(指令.js:)

app.directive('fileModel', ['$parse',function ($parse) {
return{
    scope: {
        file: '='
    },
    restrict: 'A',
    link: function(scope, element, attrs){
        var model = $parse(attrs.fileModel)
        var modelSetter = model.assign;

        element.bind('change', function(){
            var file = event.target.files[0];
            scope.file = file ? file : undefined;
            scope.$apply();
        })
    }
}
}])

url.py:

(url.py:)

urlpatterns = [
path('uploadFile/',UploadFileDataView.as_view())
]
Settings.py:

MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_file')
MEDIA_URL = '/media/'

views.py:

(views.py:)

def uploadFile(request):
if request.method == 'POST':
    # When files are submitted to the server, the file data ends up placed in request.FILES.
    form = UploadFile(request.POST, request.FILES)
    if form.is_valid():
        # file is saved
        form.save()
        messages.success(request, 'Your file has been uploaded successfully!', extra_tags='alert')
else:
    form = UploadFile()
return render(request, 'upload.html', {'form': form})
  1. What should I replace the upload.html with if my program returns UploadFileDataView.as_view()?

    (如果我的程序返回UploadFileDataView.as_view(),我应该用upload.html替换什么?)

    2. If I were to try:

    (2.如果我要尝试:)

    def uploadFile(request): if request.method == 'POST': # When files are submitted to the server, the file data ends up placed in request.FILES. form = UploadFile(request.POST, request.FILES) if form.is_valid(): # file is saved form.save() messages.success(request, 'Your file has been uploaded successfully!', extra_tags='alert') else: messages.error(request, 'Error! Your file is not uploaded successfully!', extra_tags='alert') else: form = UploadFile() return render(request, 'upload.html', {'form': form}) def uploadFile(request): if request.method == 'POST': # When files are submitted to the server, the file data ends up placed in request.FILES. form = UploadFile(request.POST, request.FILES) if form.is_valid(): # file is saved form.save() messages.success(request, 'Your file has been uploaded successfully!', extra_tags='alert') else: messages.error(request, 'Error! Your file is not uploaded successfully!', extra_tags='alert') else: form = UploadFile() return render(request, 'upload.html', {'form': form}) I will have an "Unexpected Indent" error at the else statement.

    (def uploadFile(request): if request.method == 'POST': # When files are submitted to the server, the file data ends up placed in request.FILES. form = UploadFile(request.POST, request.FILES) if form.is_valid(): # file is saved form.save() messages.success(request, 'Your file has been uploaded successfully!', extra_tags='alert') else: messages.error(request, 'Error! Your file is not uploaded successfully!', extra_tags='alert') else: form = UploadFile() return render(request, 'upload.html', {'form': form}) else语句中将出现“意外缩进”错误。)

    Why?

    (为什么?)

model.py:

(model.py:)

class UploadFile(models.Model):
file = models.FileField(upload_to="../file" ,null= True, blank=True)
title = models.CharField(max_length=10)
file = models.FileField('Uploaded File', validators=[FileExtensionValidator(['pdf'])])

Sorry, I'm new to AngularJS + Django, so any help would be appreciated.

(抱歉,我是AngularJS + Django的新手,所以我们将不胜感激。)

Thank you!

(谢谢!)

  ask by user3774763 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...