Django Ajax上传图片 [英] Django ajax upload image

查看:290
本文介绍了Django Ajax上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用不带Django表单的Ajax上传图像.

I try to upload image, using Ajax without django forms.

它不返回错误. 没关系,它保存在数据库名称"和描述"中,但不保存图像":(

It not return errors. Everything it's ok, it save in database "name" and "description" but not save "image" :(

我的代码:

views.py

def add(request):
articles = Article.objects.all()
if request.method == 'POST':
     if request.is_ajax():
        name = request.POST.get('name')
        description = request.POST.get('description')
        icon = request.FILES.get('icon')
        article_new = Article(
            name=name,
            description=description,
            icon=icon
        )
        article_new.save()

return render_to_response('home.html', {'articles':articles}, context_instance=RequestContext(request))

models.py

models.py

 class Article(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)
    description = models.TextField()
    icon = ThumbnailerImageField(upload_to='uploads')

html

 <form  method="POST"  enctype="multipart/form-data">
  {% csrf_token %}
      <input type="text" id="inputName">
      <input type="text" id="inputDescription">
      <input type="file" id="inputFile">
      <button id="submit"  type="submit">Add</button>
  </form>

javascript

javascript

 //For doing AJAX post
 $("#submit").click(function(e) {
    e.preventDefault();
    var name = $('#inputName').val();  
    var description = $('#inputDescription').val();
    var icon = $('#inputFile').val();


//This is the Ajax post.Observe carefully. It is nothing but details of where_to_post,what_to_post
$.ajax({
    url : "/add", // the endpoint,commonly same url
    type : "POST", // http method
    data : { csrfmiddlewaretoken : csrftoken,
    name : name,
    description : description,
    icon: icon
    }, // data sent with the post request
        // handle a successful response
        success : function(json) {
        console.log(json); // another sanity check
        },
        // handle a non-successful response
        error : function(xhr,errmsg,err) {
        console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
});

推荐答案

这里的问题是Ajax代码,您不能通过变量直接发送图像.

The issue here is with the Ajax code, you cannot directly send the image via a variable.

为此,您必须创建FormData,然后将文件添加到其中,可以在此处找到示例: 通过Ajax发送图像.

To do so, you would have to create FormData and then add the file to it, an example can be found here: Send Images Via Ajax.

或者,只需使用现有的 jquery Ajax表单插件即可为您完成所有艰苦的工作

Or, simply use the already existing jquery Ajax Form Plugin which does all the hard work for you.

您的选择,希望对您有所帮助:)

Your choice, hope this helps :)

这篇关于Django Ajax上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆