I am experiencing difficulties with uploading files via ajax without sing html form. My case is like this:
- I have a textarea
- I would like to zip the content of that textarea and upload it to the server via AJAX (right now I am using JSZip)
For testing purpose, I try to create a dummy zip file to send like this (not getting textarea content):
var zip = new JSZip(); zip.file("hello1.txt", "Hello First World\n");<br/> zip.file("hello2.txt", "Hello Second World\n");<br/> var content = zip.generate();
Then I use Jquery ajax method to send, like this:
$.post("the_url", { GradeRequest : { submitter_id : "foobar", evaluationset_id : 9, mode : 1, source_file : "a.cpp", file: content } } );
But the file is not received on the server. I have read question in How can I upload files asynchronously?, but all solutions are using html form. Is there any solution which does not involve any html form ?
Thanks in advance.
In the server side, I'm using Yii PHP Framework:
$model = $this->model;
if ($model !== null && isset($_POST['GradeRequest'])) {
$model->setAttributes($_POST['GradeRequest']);
if ($model->validate()) {
if (isset($_FILES['GradeRequest']['tmp_name']['file']) && $_FILES['GradeRequest']['tmp_name']['file'] !== "") {
$model->file = file_get_contents($_FILES['GradeRequest']['tmp_name']['file']);
$model->source_file = $_FILES['GradeRequest']['name']['file'];
}
$this->setReply(true, "Ok");
$model->client_id = $this->clientId;
$model->request_id = $this->requestRecord->id;
$model->save();
} else {
$this->setReply(false, $model->getErrors());
}
}
As a proof of concept, I have created a form version like this and it works (the file got uploaded to the server):
<form enctype="multipart/form-data" method="post" action="[the_url]>
EvaluationSet id: <input type="text" name="GradeRequest[evaluationset_id]" /><br />
<input type="hidden" name="GradeRequest[mode]" value="0" />
<input type="hidden" name="GradeRequest[submitter_id]" value="Someone" />
Source file : <input type="text" name="GradeRequest[source_file]" /><br />
File : <input type="file" name="GradeRequest[file]" /><br />
<input type="submit" />