Upload a CSV file using AJAX in Django - javascript

I want to upload a CSV file using ajax query.
Template:
<form id="attendance-form" method="POST" enctype="multipart/form-data">
<input type="file" id="upload-attendance" name="employee-attendance-file">
</form>
AJAX:
$("#upload-attendance").change(function(e) {
e.preventDefault(); // disables submit's default action
var input = $("#upload-attendance")[0];
var employeeAttendanceFile = new FormData();
employeeAttendanceFile.append("attendance-file", $('#upload-attendance')[0].files[0]);
console.log(employeeAttendanceFile);
$.ajax({
url: '{% url "attendance:employee-attendance-upload" %}',
type: 'POST',
headers:{
"X-CSRFToken": '{{ csrf_token }}'
},
data: {
"employee_attendance_file": employeeAttendanceFile,
},
dataType: "json",
success: function(data) {
data = JSON.parse(data); // converts string of json to object
},
cache: false,
processData: false,
contentType: false,
});
});
After uploading a CSV file, when I console.log the file variable (console.log(employeeAttendanceFile);) nothing returns. When I fetch the ajax request from django view, it also returns None (print(csv_file)).
# views.py
class ImportEmployeeAttendanceAJAX( View):
def post(self, request):
csv_file = request.FILES.get("employee_attendance_file")
print(csv_file)
What am I doing wrong?

When uploading data via a FormData object you have to pass it directly
data: employeeAttendanceFile,
Also, the name you set for the file in the upload has to match when you try to access it.
csv_file = request.FILES.get("attendance-file")

Related

How can I send a file and a string to my backend C# from JQuery Ajax?

My UI has one input for uploading file and one input for the file's name.
I want to get both file and its name from user at the same ajax request and upload the file with the gotten name to my server.
the question is how can I get both file (binary) and the file's name from user at the same request ?
here is my try but results in 400 error.
Function in C#:
public IActionResult UploadImage(IFormFile upload, string fileWithName)
{
//some code here
}
and here is my ajax:
$("#startUploading").on("click",function() {
var fileInput = $.trim($("#myfile").val());
var formData = new FormData();
formData.append('upload', $('#myfile')[0].files[0]);
formData.append('pathWithName', $("#fileAddressUploadTo").val());
$.ajax({
url: apiUrl+'/api/V1/Servers/UploadImage',
type: 'POST',
data: formData,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem('token'));
},
cache: false,
processData: false,
contentType: false
});
});
400 error means bad request, but per my test I found it worked for me. So I'm afraid the issue in your code may relate to $('#myfile')[0].files[0], see my code below
<div>
<input type="file" id="uploadFile" />
<button id="btn4">upload</button>
</div>
$("#btn4").click(function(){
var form = new FormData();
var temp = $('#uploadFile').prop('files');
form.append("file",temp[0]);
form.append("name","myFile");
console.log(form);
$.ajax({
url: 'https://localhost:44321/hello/upload',
type: 'POST',
data: form,
cache:false,
contentType:false,//stop jquery auto convert form type to default x-www-form-urlencoded
processData:false,
success: function (d) {
alert(d)
}
});
});
public string upload(IFormFile file, string name) {
return "hello";
}

Sending a file in jquery ajax POST Api call

Using Jquery, when i try to call external API by sending any file. I'm facing 415 Unsupported Media Type error. I'm trying to send my document using FormData() and header data in beforeSend() function. Suggest me correct way of sending data.
<div id="folder-browser">
<input type="file" id="file-select" name="photos" />
<button id="myButton" value="click me">click me</button>
</div>
$("#myButton").click(function() {
var myData = new FormData();
var myFile = document.getElementById("file-select");
myData.append(myFile.files[0].name, myFile.files[0]);
$.ajax({
url: 'http://10.96.45.179/RightFax/API/attachments',
data: myData,
processData: false,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic c3lzYWRtaW46cGFzc3dvcmQtMQ==');
},
type: 'POST',
success: function(result) {
console.log(result);
return result;
}
});
});
Query 2: If my document is present in URL. please let me know How can I pass the URL as a file source.
for Example:
filepath = 'http://seekvectorlogo.com/wp-content/uploads/2018/02/opentext-vector-logo-small.png';
I need to pass this file source to my external API.
When uploading binary data in a FormData object you need to set contentType: false:
$.ajax({
url: 'http://10.96.45.179/RightFax/API/attachments',
data: myData,
processData: false,
contentType: false,
// your other settings...
});

jQuery AJAX multiple files upload but send one file at a time to server using ajax

I have following html
<form id="submit-form">
<input type="file" id="resume" name="resume[]" class="inputFileHidden" multiple>
<input type="submit">
</form>
I am uploading files using ajax using formdata. The thing is that I don't want to send all files in one go using ajax. Instead I want to send single file per ajax request.
To upload files I am using following jQuery code
$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";
$.ajax({
url: url,
type: 'post',
data: formData,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
})
You can just use forEach method of FormData:
$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";
formData.forEach(function(entry) {
if (entry instanceof File) {
var fileForm = new FormData()
fileForm.append('resume', entry)
$.ajax({
url: url,
type: 'post',
data: fileForm,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
}
})
})

How to upload a file using Ajax on POST?

I know, the topics aren't missing on this subject but bear with me. I'd like to upload a file to the server using Ajax or an equivalent.
# html
<form method="post" id="Form" enctype="multipart/form-data">
{% csrf_token %} # django security
<input id="image_file" type="file" name="image_file">
<input type="submit" value="submit">
</form>
# javascript
$(document).on('submit', '#Form', function(e){
e.preventDefault();
var form_data = new FormData();
form_data.append('file', $('#image_file').get(0).files);
$.ajax({
type:'POST',
url:'my_url',
processData: false,
contentType: false,
data:{
logo:form_data,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), # django security
},
});
});
# views.py (server side)
def myFunction(request):
if request.method == 'POST':
image_file = request.FILES
...
...
I guess there's an issue with the way I configured the ajax function since on debug mode, every data are returned except the logo.
Am I doing something incorrectly?
The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES
Try this:
$(document).on('submit', '#creationOptionsForm', function(e){
e.preventDefault();
var form_data = new FormData($('#creationOptionsForm')[0]);
$.ajax({
type:'POST',
url:'/designer/results/',
processData: false,
contentType: false,
async: false,
cache: false,
data : form_data,
success: function(response){
}
});
});
Update:
basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.
While cache will force browser to not cache uploaded data to get updated data in ajax request
Official Documentation here
Looking back, the older answer is unpractical and not recommended. asnyc: false pauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload.
If you are using JQuery solely for the use of ajax, then I recommand using axios:
const axios = require('axios');
var formData = new FormData();
formData.append('imageFile', document.querySelector('#image_file').files[0]);
axios({
method: 'post',
url: 'your_url',
data: formData,
headers: {
"X-CSRFToken": CSRF_TOKEN, # django security
"content-type": "multipart/form-data"
}
}).then(function (response) {
# success
});
Axios Documentation
Jquery/Ajax answer:
var formData = new FormData();
formData.append('imageFile', $('#image_file')[0].files[0]);
formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security
$.ajax({
url : 'your_url',
type : 'POST',
data : formData,
processData: false,
contentType: false,
success : function(data) {
# success
}
});
Jquery/Ajax Documentation

Why is Flask not receiving my POST Blob?

My problem is that I'm sending a Blob to the server with FormData, but the server isn't getting it. Code looks like the following:
Flask server code:
#app.route('/save-record', methods=['POST'])
def save_record():
app.logger.debug(request.form.keys()) #Shows only the title key, not the file key
Client JS Code:
var save = function() {
var form = new FormData();
form.append('file', record.blob, record.filename);
form.append('title', searchedObj.title);
//Chrome inspector shows that the post data includes a file and a title.
$.ajax({
type: 'POST',
url: '/save-record',
data: form,
cache: false,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
Check request.files for the file.
#app.route('/save-record', methods=['POST'])
def save_record():
app.logger.debug(request.files['file'].filename)

Categories