'Save uploaded file Django Jquery Ajax
I am quite new in Python and Django and because im working on a big porject it's a bit difficult to see what I'm doing wrong. I would like to save the uploaded File in my repository folder.
<form action="/action_page.php" enctype="multipart/form-data">
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile" multiple="multiple" />
<br /><br />
<input id="upload_submit" type="submit" />
</form>
This is my views file, I dont really understand how the communication between the modules work here
@csrf_exempt
def get_text(self, request):
rand_int = random.random()
return JsonResponse({"text": "Random number: " + str(rand_int)}, status=200)
@csrf_exempt
def save_uploaded_file(self, request):
rand_int = random.random()
return JsonResponse({"text": "Random number: " + str(rand_int)}, status=200)
My urls look like this
urlpatterns = [
path("admin/", admin.site.urls),
path("save_uploaded_file/", url_Handler_Wrapper.save_uploaded_file,
name="save_uploaded_file"),
path("get_text/", url_Handler_Wrapper.get_text, name="get_text"),
path("tasks/", url_Handler_Wrapper.run_task, name="run_task"),
path("", url_Handler_Wrapper.home, name="home"),
]
And this is my javascript
$('#upload_submit').on('click', function() {
var formData = new FormData(Document.querySelector('#myfile'))
$.ajax({
url: '/save_uploaded_file/',
type: 'POST',
data: formData,
success: function (response) {
if (response) {
formData.write("/")
}
},
error: function (error) {
console.log(error)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
