django项目添加图片上传功能

第一步,在settings.py中加入如下:

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

第二步,在view视图中添加如下函数(restful是我封装的函数,可以看另外一篇文章查看内容)

@require_POST
def upload(request):
    file = request.FILES.get(‘file‘)
    name = file.name
    with open(os.path.join(settings.MEDIA_ROOT,name), ‘wb‘) as f:
        for chunk in file.chunks():
            f.write(chunk)
    url = request.build_absolute_uri(settings.MEDIA_URL+name)
    return restful.result(data={‘url‘: url})

第三步,编写ajax.js来实现通过ajax发送图片到后台,这里要注意,图片必须通过formData函数来封装,并且在发送post请求是需要加入额外两个参数(process和contentType)

function Banners() {
    var self = this;
    self.counts = $(‘.loop-img‘).length;

}

//cms后台管理系统修改轮播图片
Banners.prototype.addbanners = function () {
    var self = this;
    var addBtn = $(‘.cms-header .button button‘);
    addBtn.click(function () {
        console.log(self.counts);
        var tpl = template(‘add-banners‘,{‘counts‘: self.counts});
        var bannerGrouplist = $(‘.row‘);
        bannerGrouplist.prepend(tpl);
        var bannerItem = bannerGrouplist.find(‘.loop-img:first‘);
        self.addimg(bannerItem);
        self.counts += 1;
    });
};
//点击添加图片按钮事件
Banners.prototype.addimg = function (bannerItem) {
    var inputimg = bannerItem.find(‘img‘);
    var self = this;
    inputimg.click(function () {
        var inputimage = $(this).parent().siblings(‘#addimg‘);
        inputimage.click();
        inputimage.change(function () {
            var file = this.files[0];
            var formdata = new FormData();
            formdata.append(‘file‘,file);
            $.post({
                ‘url‘: ‘/cms/upload/‘,
                ‘data‘: formdata,
                ‘processData‘: false,
                ‘contentType‘: false,
                ‘success‘: function (result) {
                    if (result.code === 200) {
                        var url = result.data.url;
                        console.log($(this));
                        inputimg.attr(‘src‘,url);
                    }
                }
            })
        })
    });


};


Banners.prototype.run = function () {
    this.addbanners();
};

$(function () {
    var banners = new Banners();
    banners.run();
});

结果示例图如下:

django项目添加图片上传功能

相关推荐