1. 程式人生 > 實用技巧 >Django 檔案上傳

Django 檔案上傳

form表單上傳檔案

{% csrf_token %}
    使用者名稱:<input type="text" name="username" >

    頭像:<input type="file" name="avatar" multiple>

    <input type="submit">

</form>

ajax上傳檔案

使用者名稱:<input type="text" name="username" id="username">

頭像:<input type="file" name="avatar" id="avatar">
<button id="ajax_btn">上傳</button>


    $('#ajax_btn').click(function () {

        var uname = $('#username').val();
        var file_obj = $('#avatar')[0].files[0];

        var formdata = new FormData();
        formdata.append('username',uname);
        formdata.append('csrfmiddlewaretoken','{{ csrf_token }}');
        formdata.append('avatar',file_obj);


        $.ajax({
            url:'/login/',
            type:'post',
            data:formdata,
            processData: false ,    // 不處理資料
            contentType: false,    // 不設定內容型別
            success:function (res) {
                console.log(res);
            }
        })
    })

檢視程式碼

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        # print(request.POST)
        # print(request.FILES)
        file_obj = request.FILES.get('avatar')
        print(file_obj) // JS語言.md <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
        name = file_obj.name
        print(name)    //  JS語言.md <class 'str'>

        # with open(fr'C:\Users\oldboy\Desktop\Pointofix\{name}', 'wb') as f:
        print(type(file_obj))
        with open(name, 'wb') as f:
			# 方式1
            # for i in file_obj:  # \r\n
			# 方式2
            # for i in file_obj.chunks():  # \r\n
            for i in file_obj.chunks():  # \r\n  讀取65536B
                f.write(i)


        return HttpResponse('ok')