Django project adds image upload function

The first step is to add the following to settings.py:

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

The second step is to add the following function in the view view (restful is my encapsulated function, you can see another article to view the content)

@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})

The third step is to write ajax.js to send the picture to the background through ajax. It should be noted here that the picture must be encapsulated by the formData function, and two additional parameters (process and contentType) need to be added when sending the post request.

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();
});

An example of the results is as follows:

 

Guess you like

Origin www.cnblogs.com/fengzi7314/p/12729156.html