Search code examples
javascriptdjangofile-iofetch

JS fetch multiple pics (as FormData) to Django to save


I'm sure this seems so basic but it's my first attempt to try to upload files to django using fetch and I'm not sure how to manipulate and access FormData in Django.
This create so many non-working jpg files. How to fix it?
HTML:

<div>  
   <textarea></textarea>
   <input type="file" multiple></input>
   <button onClick="dothis()" >Sound</button>
</div>

JS:

    function dothis(){
        let data = new FormData();
        let input = event.target.previousElementSibling;
        for (let file of input.files){
            d.append( "hello", file);
        }

        fetch("/images", {
            credentials: "include",
            method: "POST",
            mode: "same-origin",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json",  // or "multipart/form-data"??
                "X-CSRFToken": csrf
            },
            body: data
        })
        .then(response => response.json())
        .then(result => {
            console.log("Well?");
        })

Django views.by:

def images(request):
    print(request.body)
    form = request.body
    filename = 0
    for ff in form:
       filename += 1
       with open(f"{filename}.jpg", "wb+") as f:
           f.write(ff)
    return JsonResponse(status=201)

Solution

  • Figured it out...

    Removed Content-Type from fetch's headers
    and
    Accesessed files in views.by with request.FILES