Save form file data to GCS using Django

Kepler·2020년 6월 17일
0

Premise: A user wants to upload an audio file that is stored in her computer to a specific Google Cloud Server.

Frontend

HTML

<input type="file" id="audiofileUpload" name="place_auido_add">
<button type= "submit" class= "submitUpload" onclick="saveAudio('{{ place.id }}')">Submit</button>

JS

  1. Create a form data using JS's new FormData() and add a key/value pair using .append.
const form = new FormData()

form.append('file', document.getElementById('audiofileUpload').files[0])
form.append('document_type', document_type)
form.append('language', selected_value)
  1. In your ajax request, set contentType, processData to false
$.ajax({
  url: "/db/places/" + place_id + "/save_audio/",
  type: 'POST',
  contentType : false,
  data: form,
  processData: false,
  success: function (response) {
    alert("Audio is successfully uploaded.")
    location.reload();
  },
  error: function(response) {
    alert("Error occured.")
  }
})(jQuery);

Django

  1. Create a django's form data to accept the request form data sent via ajax request.
class UploadFileForm(forms.Form):
    document_type = forms.Field()
    language = forms.TextInput()
    file = forms.FileField()

Django form class

n a similar way that a model class’s fields map to database fields, a form class’s fields map to HTML form <input> elements. (A ModelForm maps a model class’s fields to HTML form <input> elements via a Form; this is what the Django admin is based upon.)

  1. Create a function to ave a file to temporary folder.
  • open with 'wb+' mode, to write a binary audio file.
  • write the file by chunks using for loop
def save_to_tmp_folder(form_data, source_file_name):
    with open(source_file_name, 'wb+') as destination:
        for chunk in form_data.chunks():
            destination.write(chunk)
  1. Using a tempfile.gettempdir() to get the temp folder's path and suing save_to_tmp_folder function to write the file into the destination. UseUploadFileForm() and pass request.POST and request.FILES as arguments.

request.POST

If the form is submitted using a POST request, the view will once again create a form instance and populate it with data from the request: form = NameForm(request.POST) This is called “binding data to the form” (it is now a bound form).

request.FILES

when you use the form, you need to bind the file data. File data is handled separately to normal form data, so when your form contains a FileField and ImageField, you will need to specify a second argument when you bind your form.

def place_save_audio(request, place_id):
        folder_path = tempfile.gettempdir() 
        
        source_file_name = f"{folder_path}.mp3"

        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            save_to_tmp_folder(request.FILES['file'], source_file_name)
        else:
            print ('form was invalid')
  1. Post the file into the GCS using upload_from_file() method.
    Learn more on how to upload objects into GCS.
	# post the new audio to bucket
    	destination_blob_name = "xxxx.mp3"
        bucket = storage.Client().bucket('bucket_name')
        
        blob = bucket.blob(destination_blob_name)
       	blob.upload_from_filename(source_file_name)   

        return HttpResponse(status=200)

What is BLOB?

A Binary Large OBject (BLOB) is a collection of binary data stored as a single entity in a database management system. Blobs are typically images, audio or other multimedia objects, though sometimes binary executable code is stored as a blob. Database support for blobs is not universal.
In GCS, it refers to a wrapper around Cloud Storage’s concept of an Object. More on this.

profile
🔰

0개의 댓글