简体   繁体   English

使用javascript和django将文本文件上传到服务器中的某个文件夹

[英]using javascript and django to upload a text file to some folder in server

I need to upload a text file which contains some data ,from my local filesystem to say {{MEDIA_URL}}/uploadfolder .This file is to be processed by one of the functions in my django view. 我需要从我的local filesystem上传一个包含一些数据的文本文件,说{{MEDIA_URL}}/uploadfolder 。这个文件将由我的django视图中的一个函数处理。

I created an <input type="file" id="fselect" > in my html page.I created a javascript file in which I tried to call the upload function as below 我在我的html页面中创建了一个<input type="file" id="fselect" > 。我创建了一个javascript文件,我尝试在其中调用上传函数,如下所示

 $(document).ready(function(){
      ...
      $('#fselect').change(function(){ 
         file=$('#fselect').get(0).files[0];
         uploadFile(file);
      }

});

When I used firebug,and tried 当我使用萤火虫,并尝试

file=$('#fselect').get(0).files[0]

I was able to get the File object which is the text file selected using the input element.How can I call the django view with this File object?In the django view,what datatype will this File object be? 我能够获取File对象,它是使用input元素选择的文本文件。如何使用此File对象调用django视图?在django视图中,此File对象将是什么数据类型?

def storeAndProcessFile(request,file):
    pass

Before I get into any javascript, first you should understand how files are generally uploaded and handled using Django. 在进入任何javascript之前,首先应该了解如何使用Django上传和处理文件。 Consider the following html form: 请考虑以下html表单:

<form method="post" action="/foo/url/">
    <input type="file" name="foofile">
    <input type="submit" value="Upload">
</form>

So when the user clicks submit button, the browser will upload that file to the /foo/url/ using HTTP method POST . 因此,当用户单击“提交”按钮时,浏览器将使用HTTP方法POST将该文件上载到/foo/url/ Then on the server side in Django, the url /foo/url/ will be mapped to some view. 然后在Django的服务器端,url /foo/url/将映射到某个视图。 In your case it will be storeAndProcessFile . 在你的情况下,它将是storeAndProcessFile So what the view will have to do is take the file which was uploaded and store that to disk (or possibly some other storage system). 所以视图必须做的是获取上传的文件并将其存储到磁盘(或可能是其他存储系统)。

Now the view does not get the file as one of its function parameters like you showed in your question. 现在,视图不会将文件作为您在问题中显示的函数参数之一。 That is because how GET, POST, and FILE data is passed in HTTP requests. 这是因为如何在HTTP请求中传递GET,POST和FILE数据。 So the file will actually be a part of the request parameter inside the view. 因此该文件实际上是视图中request参数的一部分。 You would be able to reference the file by request.FILES['foofile'] . 您可以通过request.FILES['foofile']引用该文件。

To just store the file to disk, your view might look something like: 要将文件存储到磁盘,您的视图可能如下所示:

def storeAndProcessFile(request):
    # make sure the the request method is POST
    if request.method != 'POST':
        return HttpResponseBadRequest('Only POST requests are allowed')
    # now get the uploaded file
    file = request.FILES['foofile']
    # the file is going to be an instance of UploadedFile
    with open('/destination/path/%s' % file.name, 'wb+') as dest:
        for chunk in file.chunks():
            dest.write(chunk)
    # return success message
    return HttpResponse('File uploaded')

This code is pretty much out of Django documentation. 这段代码几乎不属于Django文档。 If you want to know more, you can read it here . 如果您想了解更多信息,可以在此处阅读。

As for Javascript, there are ton of jQuery plugins where can upload files using ajax or even multiple files at once. 至于Javascript,有大量的jQuery插件,可以使用ajax甚至多个文件一次上传文件。 I really like this library. 我真的很喜欢这个图书馆。 It has many features including sending multiple files. 它有许多功能,包括发送多个文件。 However if that is too much you can just do a search for jQuery file upload plugin and there are ton of them but I haven't tested any others recently so can't give any recommendation. 然而,如果这太多了你可以只搜索jQuery文件上传插件,并且有很多但是我最近没有测试任何其他的,所以不能给出任何建议。

There is however one thing to bear in mind when making ajax requests to a Django site, which is CSRF. 但是,在向Django站点(即CSRF)发出ajax请求时,需要记住一件事。 Since Django 1.2.5 they changed how CSRF is validated and that can break many upload libraries. 自Django 1.2.5以来,他们改变了CSRF的验证方式,并且可以打破许多上传库。 If you don't need to worry about it, you can always add csrf_exempt decorator: 如果您不需要担心它,您可以随时添加csrf_exempt装饰器:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def storeAndProcessFile(request):
    ...

If however you need CSRF, you can take a look at sample implementation of integrating jQuery file uploader with CSRF enabled here . 但是,如果您需要CSRF,可以查看在此处启用CSRF的集成jQuery文件上传器的示例实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM