I have an application that I am building. The app creates a json file, then a jar file is uploaded and the json file is inserted into the jar, and the new jar is returned.
I have created a basic HTML form and PHP file that currently works, but the user must select both the jar and the json file to upload. I need to modify this now so that the user chooses the zip file, but the form would select the JSON from the JS.
THE HTML:
<form id="jar-form">
<div class="mb-3">
<label for="test-jar-upload" class="form-label">Select Jar File Files:</label>
<input type="file" id="test-jar-upload" name="jar" accept=".jar" class="form-control">
</div>
<div class="mb-3">
<button type="button" class="btn btn-primary" ng-click="export.exTest()" name="upload_file">Submit</button>
</div>
THE JS:
$scope.export.exTest = function(){
console.log('New Manual Submit');
let formData = new FormData();
let tFile = new Blob([JSON.stringify($scope.export.file)], {type: 'application/json'});
formData.append('jar',document.getElementById('test-jar-upload').files[0]);
formData.append('desc',tFile);
$scope.newData = formData;
$.ajax({
url: './assets/api/test.php',
data: formData,
type: "POST",
contentType: false,
processData: false
})
}
The AJAX call was taken from another answer, but doesn't successfully open the test.php file. If I change the path, I do get a 404 error returned.
Related
I have a form in datatable as follows.
<form method="post" enctype="multipart/form-data">
<label for="file_'+row["course_id"]+'">
<i class="far fa-2x fa-file-pdf f-gray"></i>
</label>
<input type="file" id="file_'+row["course_id"]+'">
</form>
This shows a pdf button inside datatable for file upload. Onclick it will show a file browser for file selection.
Using javascript's FormData() I am passing the file to Laravel controller.
$(document).on("change", "[id^=file_]", function(e) {
var file_data = this.files[0];
var form_data = new FormData();
form_data.append("pdf_file", file_data);
$.ajax({
url: "/pdfUpload",
cache: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
$('div.flash-message').html(data).fadeOut(5000);
}
});
});
The request headers is as follows:
But the following code says there is no file and is returning null.
public function upload(\Google_Service_Drive $service, Request $request){
if ($request->hasFile('pdf_file')) {
dump('yes');
}else{
dump('no');
}
dd($request->pdf_file);
$data = file_get_contents(?)
}
Output:
Any help on what I'm missing here?
Also, I need to get $data = file_get_contents(?) working. What should I pass here
I'm new to this. Could you show me how to send a file to server using ajax. I could submit to my server a String, but I don't know how would ajax handle a File?
upload_stuff.js
$(document).on('submit', '#CustomerRequest', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/create_request',
data:{
ajax_file1:$('#html_file1').val(),
ajax_file2:$('#html_file2').val(),
ajax_file2:$('#html_file3').val(),
...
view.py
def create_request (request):
if request.method == "POST":
server_file1 = request.FILES('ajax_files1')
server_file2 = request.FILES('ajax_file2')
server_file3 = request.FILES('ajax_file3')
I do have csrf_token and and enctype="multipart/form-data" on my html form
I have tried this and it works fine, Hope it works for you too.
First create a relevant form in your forms.py file which would look like this:
from django import forms
class FileForm(forms.Form):
file = forms.FileField(required=True)
In your html file it would look like:
<div>
<form id="file_form" action="/application/new_file/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label class="btn btn-info btn-xs" for="subgroup_file" style="background-color: #042d63;border-color: #dddddd;border-width: 2px;color: white;padding: 5px 21px;" id="send_file" data-toggle="tooltip" data-placement="auto top" title="Choose The File">
<input id="the_file" name="file" type="file" style="display:none;">
<span class="glyphicon glyphicon-paperclip"></span>
</label>
<input type="submit" id="file_form_submit" class="my-small-btn" value="Submit" data-toggle="tooltip" data-placement="auto top" title="Submit File">
</form>
</div>
then the id=file_form can trigger this:
$('#file_form').submit(function(event){
event.preventDefault();
var formData = new FormData(this); //get data of form elements for submission
formData.append('sg_id', '{{ sg_id }}'); //add additional data to form's data
$.ajax({
url: "/application/new_file/",
type: "POST",
enctype: 'multipart/form-data',
data: formData,
processData: false,
contentType: false,
cache: false,
success: function (data) {
if(! data.created){
location.reload();
} else if(! data.valid_extension){
swal({
title: 'You can only submit PDF files',
text: '',
icon: 'error',
timer: 5000,
});
}
}
});
});
Here I have also added a sweet alert which informs the user he/she is only allowed to upload PDF files. The URL finally takes you from urls.py to a fucntion named saveFile in views.py which would something like this:
def saveFile(request):
if(request.user != AnonymousUser()):
try:
if request.method == 'POST':
file_form = FileForm(request.POST, request.FILES)
sg_id = request.POST.get("sg_id")
subgroup = SubGroup.objects.get(pk=sg_id)
if(file_form.is_valid()):
file = file_form.cleaned_data["file"]
name = str(file)
f, extension = os.path.splitext(name)
if(extension in valid_extensions):
obj = Files.objects.create(
file = file,
subgroup = subgroup,
creator = request.user,
created_at = datetime.datetime.now(),
name = name
)
.......
.......
.......
The SubGroup and Files are objects defined in models.py which connect you to the database.
i don't know if this might be helpful or not, but in JQuery the $('#fileinput').val() doesn't return "Ajax friendly" file data, try using document.getElementById('fileinput').files[0]; to get the file data using raw javascript and try to add these options on the ajax request
contentType: false,
processData: false,
I'm trying to upload an image through a form to a url/api.
I call handleImgUpload() method on submitting the form.
The problem is that the request sent is empty.
I think that new FormData(this) does not work with react or something.
There's another function that sets the image path.
handleImgUpload(e){
e.preventDefault();
$.ajax({
url: "my url goes here", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){ // A function to be called if request succeeds
console.log(new FormData(this));
}
});
}
here is the form:
<form id="uploadimage" onSubmit={this.handleImgUpload} action="" method="post" encType="multipart/form-data">
<Row id="image_preview" className="row">
<img id="previewing" src={this.state.imgPath}/>
</Row>
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="image" id="file" onChange={this.handleImgChange} required />
<Button type="submit" className="btn btn-primary" id="upload">Upload</Button>
</div>
</form>
this is going to be the React component, not the form, which can be found in event.target
handleImgUpload(e) {
e.preventDefault()
let formData = new FormData(e.target)
for (let [key, val] of d.entries()) {
console.log(key, val) <-- should log the correct form data
}
// ajax stuff
}
I have looked through the numerous Stackoverflow questions, various tutorials and youtube vids and so far none (that I have found) address this issue for me...
I have a form to load a single file. It submits this fine without ajax.
<form asp-action="FileIndexView"
asp-controller="SuburbsAndPostcodesAdmin"
method="post"
enctype="multipart/form-data">
<div class="form-horizontal">
<div class="form-group">
<label class="col-md-4 control-label">Select the Suburbs and Postcodes latest CSV File:</label>
<input type="file"
name="CSVFile"
id="txtFileUpload"
class="col-md-8 control-label" />
</div>
<div class="form-group">
<input type="submit"
name="Submit"
value="Submit"
class="col-md-1 btn btn-primary"
disabled="disabled"
id="SubmitFile" />
</div>
</div>
I have an Ajax POST method. its called when you click the submit button. All good.
Here is the code.
$('#SubmitFile').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
//var fileUpload = input.files[0];
var url = "/SuburbsAndPostcodesAdmin/test";
var connId = $.connection.hub.id;
var fd = new FormData();
fd.append('File', input.files[0]);
fd.append('connId', connId);
$.ajax({
type: "POST",
url: url,
data: fd,
processData: false,
contentType: false,
});
When I step through this it errors on the:
"fd.append('File', input.files[0]);"
line with the following error in the console.
ReferenceError: input is not defined
<anonymous>
FileIndexView:127
n.event.dispatch()
jquery.min.js:3
n.event.add/r.handle()
jquery.min.js:3
EventLoop.prototype.enter()
...
Why is this erroring on this line?
How should it read so it is defined?
What should the file name be and why? (does this need to address back to the form)
The problem is with input.files[0] because here input is undefined.
Instead of
fd.append('File', input.files[0]); //here input is not defined
Try
fd.append('File', $("#txtFileUpload")[0].files[0]);
This "Formdata" object seems suspect. jQuery likes simple objects, i.e.
$.ajax({
type: "POST",
url: url,
data: {input: "A", somethingelse: 2, somethingmore: true},
processData: false,
contentType: false,
});
In your browser, use the developer options and go to the Network tab to see exactly what's being pushed to the server in the POST operation. I'll bet it doesn't fit what your server method is expecting, hence the exception.
EDIT
Didn't notice until now that you're trying to do file upload. It is well-documented as a pain-in-the-butt via AJAX. I've had success with a plug-in called DropZone. http://www.dropzonejs.com/
I have an HTML form with two buttons (along with other text input areas), and I have some front end javascript code to handle the submit. On the submit, I create a FormData object and store the file in it. Then I send that through an jquery ajax request to a node.js server. However, this is where the problem is - when I try to access the file in the server, the file is always undefined - i've tried accessing it with req.body, req.files, req.file but its always undefined. Is this a problem with the ajax request, or the way i'm receiving it?
upload file button:
<input id="element_3" name="element_3" class="element file required" accept="application/pdf" type="file"/>
submit button:
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit"/>
handle submit:
$('#form_1039889').submit(function(event) {
event.preventDefault();
event.stopImmediatePropagation();
var file = $('#element_3').get(0).files[0];
var fd = new FormData();
fd.append('pdf', file);
$.ajax({
url: '/addPdf',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(response) {
//success TODO code
}
});
});
relevant server code:
app.post('/addPdf', [multer({dest: "./uploads/"}).single('avatar'), function(req, res) {
console.log("file: " + req.file);
}]);
Instead of single('avatar') use single('pdf.file') because you set pdf object for file.
Name that we pass inside Single should match with form-data key. So Change .single('avatar') with .single('pdf').
So your node js code will look like this:
app.post('/addPdf', [multer({dest: "./uploads/"}).single('pdf'), function(req, res) {
console.log("file: " + req.file);
}]);