使用JQuery和Django上传图像 [英] Uploading Image Using JQuery And Django

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

问题描述

在你继续阅读之前,请相信我,当我说我已经阅读了关于这个问题的所有其他帖子,没有一个帮助。

Before you continue reading, trust me when I say I have read all the other posts on this subject, and none of them helped.

我正尝试添加图像上传功能到我的网站。我想通过ajax的帖子上传图像
。我不能得到这个工作。

I am trying to add image upload functionality to my website. I want to upload the image via an ajax post. I cannot get this working.

这是我有的:

HTML - 我有一个特殊的设置显示图像而不是愚蠢的按钮
和文本字段。我也使用onChange事件在选择图像后点击确定时自动提交。

HTML - i have a special setup so that an image is displayed instead of a stupid button and the text field. I am also using the onChange event to automatically submit when I have hit "OK" after selecting the image.

<form id="add-picture-form" method="POST" action="/api/upload_image/" enctype="multipart/form-data">{% csrf_token %}  
    <div class="thumbnails" style="width:400px;">
        <label class="cabinet BrandHeader"> 
            <input type="file" class="file" id="upload-photo" onChange="$('#add-picture-form').submit();" /> 
        </label> 
    </div>
</form> 

Jquery:

$('#add-picture-form').submit(function() { 
    //var filename = $("#upload-photo").val();
    var photo = document.getElementById("upload-photo"); 
    var file  = photo.files[0];

$.ajax({ 
    type: "POST",
    url: "/api/upload_image/",
    enctype: 'multipart/form-data',
    data: {'file': file.getAsBinary(), 'fname' : file.fileName },
    success: function(){
       alert( "Data Uploaded: ");
    }
});

    return false;   
}); 

最后我的django视图被发送到/ api / upload_image /

Finally my django view that is hit when you post to /api/upload_image/

def ajax_upload( request ):

    print request.POST
    print request.FILES

    return http.HttpResponse(simplejson.dumps([True]), mimetype='application/javascript')

我已经尝试将图像写入二进制文件,但是我无法打开已写入的数据。
为什么要使用javascript上传图像这么难?我是一个白痴,只是不使用简单的解决方案?如果是这样,请告诉我使用jQuery在Django中上传图像的最佳方式是什么。

I have tried to write the image to binary, but I cannot open that data that has written. Why is uploading an image using javascript so hard? I am an idiot and just not using a simple solution? If so, please tell me what is the best way to use jQuery to upload an image in Django.

推荐答案

尝试jQuery插件 Uploadify SWFUpload的。有人甚至为您做了Django集成,请参阅: https://github.com/tstone/django-uploadify http://blog.fogtunes.com/ 2009/11 / howto-integration-swfupload-with-django /

Try the jQuery plugins Uploadify or SWFUpload. Someone even did the Django integration for you, see: https://github.com/tstone/django-uploadify and http://blog.fogtunes.com/2009/11/howto-integrate-swfupload-with-django/.

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

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