I'm trying to upload a file along with a string to MongoDB using FormData() function in Ajax. I know that Ajax tends to stringify all the passed data unless we set processData: false
and thus I have to use FormData for both the file and the string.
Snippet of HTML
<h5 class="modal-title h5Modal" id="htmlIP"></h5>
<div class="form-group">
<label for="fileUpload">Choose a File To Upload:</label>
<input type="file" id="fileUpload" accept="image/*,.pdf,.pptx" class="file-path">
</div>
<div class="modal-footer">
<button class="btn btn-primary submitFile" data dismiss="modal" > Submit </button>
</div>
Python
def FileSubmit(request):
if request.method == "GET":
ip = request.GET['IP']
file = request.GET['fileUpload']
else:
ip = ''
res = Pc.uploadToDB(ip, file)
data = {
'version' : res,
}
return JsonResponse(data)
Where uploadToDB function looks for the document with the provided ip inside MongoDB and updates the file field.
And here is my Ajax function:
$(document).ready(function() {
$('.submitFile').on('click,function(){
var rowID = $('#htmlIP').text();
formdata = new FormData();
var file = document.getElementById('fileUpload').files[0];
formdata.append('file', file);
$.ajax({
type: "GET",
url: 'FileSubmit/' + rowID,
//data: {
// 'IP': rowID,
// 'fileUpload': file,
//},
data: formdata,
processData: false,
contentType: false,
success: function(data){
alert(data.version);
window.location.reload();
},
error: function(err){
alert(err);
}
});
});
});
As you can see, I have commented out my first approach to use data.
When I try to upload a file using these functions, I get the following error:
Not Found: Path/to/FileSubmit/XXX.XXX.XXX.XXX
which is understandable as I provided rowID as a url when it shouldn't be. But this is the closest I could get to being able to grab the file and the ip correctly.
Whenever I get rid of rowID inside the url and try a different solution I get the same following error which points to the request.GET line written in Python:
MultiValueDictKeyError: "u'IP'"
Which means it isn't able to read the IP correctly.
I have looked at most of the answers provided in Send FormData and String Data Together Through JQuery AJAX? However, most of them did not help me unfortunately as they focus on uploading an array of strings rather than one instance.
Is there any way to append the string to formdata or another approach I'm not aware of ? Any help or suggestions are greatly appreciated.