html五、django上傳文件

  1. 使用簡單的表單上傳文件到django框架
    form表單須要指定 enctype="multipart/form-data"
    前端代碼:
<!DOCTYPE html>
<html>
    <head>
        <title>uploadFile</title>

    </head>
    <body>

        <form method="POST" action="/upload"  enctype="multipart/form-data">
            <input type="file" name="myFile">
            <input type="submit" value="提交" />
        </form>

    </body>
</html>

後端代碼:html

def upload(request):
    ##request.FILES 爲類字典類型,健爲前段name指定的值,字典值爲UploadFile對象,前端form中須要指定enctype="multipart/form-data"
    ##<input type="file" name="myFile">
    uploadFileObj = request.FILES['myFile']
    uploadFileName = uploadFileObj.name
    uploadFileSize = uploadFileObj.size

    ##上傳文件
    with open(uploadFileName,"wb") as saveFile:
        for chunk in uploadFileObj.chunks():
            saveFile.write(chunk)

    return HttpResponse('file upload OK')
  1. 使用ajax上傳文件,不刷新當前頁面,後端代碼不變
    html頁面:前端

    {% load static%}
    <!DOCTYPE html>
    <html>
    <head>
        <title>uploadFile</title>
        <script src="{% static 'jquery-3.3.1.min.js' %}"></script>
        <script>
            function upload(){
                var formData = new FormData();
                var fileObj = $("#myFile")[0].files[0];
                console.log(fileObj);
                formData.append("myFile",fileObj);
                console.log(formData);
                $.ajax({
                    url:"upload",
                    type:"post",
                    data:formData,
                    contentType:false,    // 必定要有
                    processData:false,     // 必定要有,不然可能js報錯: Uncaught TypeError: Illegal invocation
                    success: function(response){
                        $('#info').text(response);
                    },
                });
    
            }
        </script>
    </head>
    <body>
    
            <input type="file" name='myFile' id='myFile'>
            <button type="button" onclick="upload()">upload</button>
    
        <div id="info"></div>
    
    </body>
    </html>
相關文章
相關標籤/搜索