Local image with Microsoft Cognitive Services - javascript

I try to import local image to Computer Vision API (OCR). But when I try to run it, it totally return nothing.
If I try to paste raw image into data: makeblob('') it work, but when I use variable from function get local image encodeImageFileAsURL(), it return nothing. I can get the raw image binary (base64), but when I try to take it into data to send to Cognitive services, it nothing happened.
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("textBase64").innerHTML = srcData;
//alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
//console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
var a = document.getElementById("textBase64").value;
function processImage() {
// **********************************************
// *** Update or verify the following values. ***
// **********************************************
makeblob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
// Replace the subscriptionKey string value with your valid subscription key.
var subscriptionKey = "SORRY I CAN'T PUBLIC MY KEY";
// Replace or verify the region.
//
// You must use the same region in your REST API call as you used to obtain your subscription keys.
// For example, if you obtained your subscription keys from the westus region, replace
// "westcentralus" in the URI below with "westus".
//
// NOTE: Free trial subscription keys are generated in the westcentralus region, so if you are using
// a free trial subscription key, you should not need to change this region.
var uriBase = "https://southeastasia.api.cognitive.microsoft.com/vision/v1.0/ocr";
// Request parameters.
var params = {
"language": "unk",
"detectOrientation ": "true",
};
// Display the image.
var sourceImageUrl = document.getElementById("inputFileToLoad").value;
document.querySelector("#sourceImage").src = sourceImageUrl;
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Content-Type", "application/octet-stream");
jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
processData: false,
// Request body.
data: makeblob("'" + a + "'"),
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ? "Error. " : errorThrown + " (" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" : (jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message : jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Optical Character Recognition (OCR):</h1>
Enter the URL to an image of printed text, then click the <strong>Read image</strong> button.
<br><br>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<textarea rows="10" cols="60" id="textBase64"></textarea>
<br><br> Image to read: <input type="text" name="inputImage" id="inputImage" value="" />
<button onclick="processImage()">Read image</button>
<br><br>
<div id="wrapper" style="width:1020px; display:table;">
<div id="jsonOutput" style="width:600px; display:table-cell;">
Response:
<br><br>
<textarea id="responseTextArea" class="UIInput" style="width:580px; height:400px;"></textarea>
</div>
<div id="imageDiv" style="width:420px; display:table-cell;">
Source image:
<br><br>
<img id="imageTest" width="400" />
<div id="imageTest"></div>
</div>
</div>
<h1>Optical Character Recognition (OCR):</h1>
Enter the URL to an image of printed text, then click the <strong>Read image</strong> button.
<br><br>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<textarea rows="10" cols="60" id="textBase64"></textarea>
<br><br> Image to read: <input type="text" name="inputImage" id="inputImage" value="" />
<button onclick="processImage()">Read image</button>
<br><br>
<div id="wrapper" style="width:1020px; display:table;">
<div id="jsonOutput" style="width:600px; display:table-cell;">
Response:
<br><br>
<textarea id="responseTextArea" class="UIInput" style="width:580px; height:400px;"></textarea>
</div>
<div id="imageDiv" style="width:420px; display:table-cell;">
Source image:
<br><br>
<img id="imageTest" width="400" />
<div id="imageTest"></div>
</div>
</div>

Since a is already a string, you don't want to introduce the extra quotes when calling makeBlob because that will cause the atob call to fail. You want to simply say:
// Request body.
data: makeblob(a),

Related

CKEditor response callback after file attached successfully

Using CKEditor to send email and upload attachments. Below is the minimal configuration I've from this source.
CKEDITOR.replace('email.Message', {
filebrowserUploadUrl: '/Controller/UploadAttachment',
extraPlugins: 'attach', // attachment plugin
toolbar: this.customToolbar, //use custom toolbar
autoCloseUpload: true, //autoClose attachment container on attachment upload
validateSize: 30, //30mb size limit
onAttachmentUpload: function(response) {
/*
the following code just utilizes the attachment upload response to generate
ticket-attachment on your page
*/
attachment_id = $(response).attr('data-id');
if (attachment_id) {
attachment = $(response).html();
$closeButton = $('<span class="attachment-close">').text('x').on('click', closeButtonEvent)
$('.ticket-attachment-container').show()
.append($('<div>', {
class: 'ticket-attachment'
}).html(attachment).append($closeButton))
.append($('<input>', {
type: 'hidden',
name: 'attachment_ids[]'
}).val(attachment_id));
}
}
});
On the Controller side I've got below code
const string scriptTag = "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}')</script>";
public ContentResult UploadAttachment()
{
string basePath = HttpContext.Server.MapPath("~/assets/Images/");
const string baseUrl = #"/ckfinder/userfiles/";
var funcNum = 0;
int.TryParse(Request["CKEditorFuncNum"], out funcNum);
if (Request.Files == null || Request.Files.Count < 1)
return BuildReturnScript(funcNum, null, "No file has been sent");
if (!System.IO.Directory.Exists(basePath))
return BuildReturnScript(funcNum, null, "basePath folder doesn't exist");
var receivedFile = Request.Files[0];
var fileName = receivedFile.FileName;
if (string.IsNullOrEmpty(fileName)) {
return BuildReturnScript(funcNum, null, "File name is empty");
}
var sFileName = System.IO.Path.GetFileName(fileName);
var nameWithFullPath = System.IO.Path.Combine(basePath, sFileName);
//Note: you may want to consider using your own naming convention for files, as this is vulnerable to overwrites
//e.g. at the moment if two users uploaded a file called image1.jpg, one would clash with the other.
//In the past, I've used Guid.NewGuid() combined with the file extension to ensure uniqueness.
receivedFile.SaveAs(nameWithFullPath);
var url = baseUrl + sFileName;
return BuildReturnScript(funcNum, url, null);
}
private ContentResult BuildReturnScript(int functionNumber, string url, string errorMessage) {
return Content(
string.Format(scriptTag, functionNumber, HttpUtility.JavaScriptStringEncode(url ? ? ""), HttpUtility.JavaScriptStringEncode(errorMessage ? ? "")),
"text/html"
);
}
Below is the response I get back inside onAttachmentUpload - function
<form enctype="multipart/form-data" method="POST" dir="ltr" lang="en" action="/Controller/UploadAttachment?CKEditor=email_Message&CKEditorFuncNum=0&langCode=en">
<label id="cke_73_label" for="cke_74_fileInput_input" style="display:none"></label>
<input style="width:100%" id="cke_74_fileInput_input" aria-labelledby="cke_73_label" type="file" name="attachment" size="38">
</form>
<script>
window.parent.CKEDITOR.tools.callFunction(98);
window.onbeforeunload = function({
window.parent.CKEDITOR.tools.callFunction(99)
});
</script>
But it is expecting some data-id for attachment id. I've no idea what the response should look like. Could someone tell me what the actual response should look like and what is the data-id its expecting as attr in response? Also, is there anyway I can upload multiple files with this?
This is how I am returning the response now and rendering the attached file. Hope it might help someone in future.
[AcceptVerbs(HttpVerbs.Post)]
public ContentResult UploadAttachment() {
string basePath = HttpContext.Server.MapPath("~/somepath");
var funcNum = 0;
int.TryParse(Request["CKEditorFuncNum"], out funcNum);
if (Request.Files == null || Request.Files.Count < 1)
return Content("No file has been sent");
if (!System.IO.Directory.Exists(basePath))
Directory.CreateDirectory(Path.Combine(basePath));
var receivedFile = Request.Files[0];
var fileName = receivedFile.FileName;
if (string.IsNullOrEmpty(fileName)) {
return Content("File name is empty");
}
var sFileName = System.IO.Path.GetFileName(fileName);
var nameWithFullPath = Path.Combine(basePath, sFileName);
receivedFile.SaveAs(nameWithFullPath);
var content = "<span data-href=\"" + nameWithFullPath + "\" data-id=\"" + funcNum + "\"><i class=\"fa fa-paperclip\"> </i> " + sFileName + "</span>";
return Content(content);
}
and on the JS side I have below code to append the uploaded file name:
CKEDITOR.replace('email.Message', {
filebrowserUploadUrl: '/Controller/UploadAttachment',
extraPlugins: 'attach', // attachment plugin
toolbar: this.customToolbar, //use custom toolbar
autoCloseUpload: true, //autoClose attachment container on attachment upload
validateSize: 30, //30mb size limit
onAttachmentUpload: function(response) {
/*
the following code just utilizes the attachment upload response to generate
ticket-attachment on your page
*/
attachment_id = $(response).attr('data-id');
if (attachment_id) {
attachment = response;
$closeButton = '<span class="attachment-close btn btn-danger float-right" style="margin-top:-7px"><i class="fa fa-trash"></i></span>'; //.on('click', closeButtonEvent)
$respDiv = '<ol class="breadcrumb navbar-breadcrumb" style="padding:18px 15px"><li style="display:block">' + attachment + $closeButton + '</li></ol>';
$('.ticket-attachment-container').show()
.append($('<div>', {
class: 'ticket-attachment'
}).html($respDiv))
.append($('<input>', {
type: 'hidden',
name: 'attachment_ids[]'
}).val(attachment_id));
$('.ticket-attachment-container').on('click', '.attachment-close', function() {
$(this).closest('.ticket-attachment').remove();
if (!$('.ticket-attachment-container .ticket-attachment').length)
$('.ticket-attachment-container').hide();
});
}
}
});

PHP - Uploading multiple files with Javascript and PHP

its me again. Im currently trying to build an multiple file uploader for my site but dont know how to get/handle all files. I think showing you the code first will be a better explanation:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>NDSLR - Demo Upload</title>
</head>
<body>
<script type="text/javascript">
function fileChange()
{
//FileList Objekt aus dem Input Element mit der ID "fileA"
var fileList = document.getElementById("fileA").files;
//File Objekt (erstes Element der FileList)
var file = fileList[0];
//File Objekt nicht vorhanden = keine Datei ausgewählt oder vom Browser nicht unterstützt
if(!file) {
return;
}
var x = substr(file.name, -4);
document.getElementById("status").innerHTML = x;
/*
if (x != ".pdf") {
document.getElementById("fileA").files = null;
file = null;
fileList = null;
alert("Wrong Data");
return;
} */
document.getElementById("fileName").innerHTML = 'Dateiname: ' + file.name;
document.getElementById("fileSize").innerHTML = 'Dateigröße: ' + file.size + ' B';
document.getElementById("progress").value = 0;
document.getElementById("prozent").innerHTML = "0%";
}
var client = null;
function uploadFile()
{
//Wieder unser File Objekt
for(i=0;i < document.getElementById("fileA").files; i++) {
var file = document.getElementById("fileA").files[i];
//FormData Objekt erzeugen
var formData = new FormData();
//XMLHttpRequest Objekt erzeugen
client = new XMLHttpRequest();
var prog = document.getElementById("progress");
if(!file)
return;
prog.value = 0;
prog.max = 100;
//Fügt dem formData Objekt unser File Objekt hinzu
formData.append("datei", file);
client.onerror = function(e) {
alert("onError");
};
client.onload = function(e) {
document.getElementById("prozent").innerHTML = "100%";
prog.value = prog.max;
};
client.upload.onprogress = function(e) {
var p = Math.round(100 / e.total * e.loaded);
document.getElementById("progress").value = p;
document.getElementById("prozent").innerHTML = p + "%";
};
client.onabort = function(e) {
alert("Upload abgebrochen");
};
client.open("POST", "upload.php");
client.send(formData);
}
}
}
function uploadAbort() {
if(client instanceof XMLHttpRequest)
//Briecht die aktuelle Übertragung ab
client.abort();
}
</script>
<form action="" method="post" enctype="multipart/form-data">
<input name="file[]" type="file" multiple="multiple" id="fileA" onchange="fileChange();"/>
<input name="upload[]" value="Upload" type="button" accept=".dem" onclick="uploadFile();" />
<input name="abort" value="Abbrechen" type="button" onclick="uploadAbort();" />
</form>
<div id="status"></div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<progress id="progress" style="margin-top:10px"></progress> <span id="prozent"></span>
</div>
</body>
</html>
So this is my HTML Code and following up my upload.php:
<?php
if (isset($_FILES['datei']))
{
move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/'.$_FILES['datei']['name']);
}
?>
My Problem currently is, that i dont know how to implement the multiple upload or better said, how to upload all files at all.
There are some tutorials in the internet, that you can simply find by googling "multiple file upload". Anyway here is one of the examples:
The HTML
<!-- IMPORTANT: FORM's enctype must be "multipart/form-data" -->
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>
Listing Multiple Files with JavaScript
//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
//empty list for now...
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
//for every file...
for (var x = 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}
The input.files property provides an array of files for which you can check the length; if there's a length, you can loop through each file and access the file paths and names.
Receiving and Handling Files with PHP
if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
PHP creates an array of the files uploaded with the given INPUT's name. This variable will always be an array within PHP.
Source
Demo
This is uploading using ajax. There are other ways such the use of iframe and jquery's $.load().
ajax_upload.js
Hmm... FormData is not IE-safe. So, you may want to resort to iframe & $.load().
function doUpload(fle_id, url_upld)
{
var upldLimit = 2000000; // 2mb by default;
if( $('#'+fle_id)[0] == undefined || $('#'+fle_id)[0].files.length == 0 ) {
alert('nothing to upload');
return;
}
// put files to formData
var tfSize = 0; // in bytes
var fd = new FormData();
$.each($('#'+fle_id)[0].files, function(i, file) {
fd.append(i, file);
tfSize = tfSize + file.size;
});
// you may check file size before sending data
if(tfSize > upldLimit) {
alert('File upload exceeded the '+(upldLimit/1000000)+' MB limit.');
return;
}
// actual data transfer
$.ajax({
url: url_upld,
cache: false,
data: fd,
type: 'POST',
contentType : false,
processData : false,
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
}
upload_form.html
Let's use jquery to make things simple.
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ajax_upload.js"></script>
<script type="text/javascript">
$(function(){
$('form').submit(function(e){
if( e.preventDefault ) e.preventDefault(); // chrome/firefox
else e.cancelBubble(); // IE
// supply file input id and upload url
doUpload( 'fle', $(this).attr('action') );
});
});
</script>
Upload
<form action="ajax_upload.php"
method="post"
enctype="multipart/form-data"
accept-charset="utf-8"
>
<input type="file" id="fle" name="fle[]" multiple >
<button type="submit">Upload</button>
</form>
ajax_upload.php
<?php
if(count($_FILES) == 0) {
echo 'Nothing uploaded.';
exit;
}
$upldPath = 'E:/stack/upload/';
foreach($_FILES as $file) {
if ($file['error'] == UPLOAD_ERR_OK) {
try {
if( !move_uploaded_file( $file["tmp_name"], $upldPath . $file['name']) ) {
// abort even if one file cannot be moved.
echo 'Cannot upload one of the files.';
exit;
}
}
catch(Exception $e) {
echo 'Cannot upload the files.';
exit;
}
} else {
// abort even if one file has error.
echo 'Cannot upload one of the files.';
exit;
}
}
echo 'Upload successful!';
?>
Here is a simple approach to solving this issue.
This FormData append method works on IE 10 up and any other browser.
let files = []
let formData = new FormData
let filesInput = document.getElementById('files')
function prepareFiles() {
files = filesInput.files
}
function uploadFiles() {
// Arrange the files as form data to be sent to php
files = Array.from(files)
files.forEach(file => formData.append('files[]', file))
// See all selected files
console.log('Files')
console.log(formData.getAll('files[]'))
// Then send to php with jquery, axios e.t.c
console.log('Server response')
$.post('/pathtophpscript', formData, (response) => {
console.log(response)
}).catch(error => console.log(error))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="uploads" id="files" onchange="prepareFiles()" multiple>
<br/><br/>
<input type="submit" name="Upload" onclick="uploadFiles()">

CodeIgniter AJAX file upload, $_FILE is empty when upload

Iam writing a script that uploads files via Drag and Drop using jQuery which reads the file on drop and adds it to an array of files like so:
var files = [];
$(document).ready(function() {
jQuery.fn.dropbox = function(config) {
var dragging = 0;
var dragEnter = function(e) {
e.stopPropagation();
e.preventDefault();
dragging++;
$(".external-drop-indicator").fadeIn();
$(".toast.toast-success").fadeIn().css("display", "inline-block");;
return false;
};
var dragOver = function(e) {
e.stopPropagation();
e.preventDefault();
return false;
};
var dragLeave = function(e) {
e.stopPropagation();
e.preventDefault();
dragging--;
if(dragging === 0) {
$(".external-drop-indicator").fadeOut();
$(".toast.toast-success").fadeOut();
}
return false;
};
var drop = function(e) {
var dt = e.dataTransfer;
var files_upload = dt.files;
e.stopPropagation();
e.preventDefault();
if(files_upload && files_upload.length > 0 && config.onDrop !== undefined) {
files.push(files_upload);
config.onDrop(files_upload);
}
$(".external-drop-indicator").fadeOut();
$(".toast.toast-success").fadeOut();
};
var applyDropbox = function(dropbox) {
dropbox.addEventListener('dragenter', dragEnter, false);
dropbox.addEventListener('dragover', dragOver, false);
dropbox.addEventListener('dragleave', dragLeave, false);
dropbox.addEventListener('drop', drop, false);
};
return this.each(function() {
applyDropbox(this);
});
};
});
In summary what it does is, adds an extended jQuery function to enable drag and drop on a certain element of the website in which the function is applied.
Then I apply the extended functionality to the body for it to enable the file Drag and Drop functionality like so:
$(document).ready(function() {
$('body').dropbox({
onDrop: function(f) {
$(f).each(function(idx, data) {
var file_name = data.name;
var extension = file_name.split('.');
file_name = extension[0];
extension = extension[1];
if(extension == 'pdf' || extension == 'xls') {
showAjaxModal(base_url + 'index.php?modal/popup/file_create/' + folder_id + '/' + extension + '/' + file_name);
} else {
$(".upload-area").append('<div class="alert alert-danger" style="display:inline-block;width:480px;"><strong>Error!</strong> File type is incorrect.</div>');
}
});
}
});
});
In summary what this does is adds the Drag and Drop functionality to the body and when a file is dropped it detects the extension of the file by splitting the name and the extension, so that I can verify that the extension of the file that was dropped is correct. Then it proceeds to show a modal to fill information about the file that is being uploaded for later submission, if the file extension is correct.
Then I proceed to fill the file information using CodeIgniter's function "form_open()" when the modal pops like so:
<?php echo form_open(base_url() . 'index.php?client/file/create/' . $param2, array('class' => 'form-horizontal form-groups-bordered validate ajax-upload', 'enctype' => 'multipart/form-data')); ?>
<div class="col-md-4 file-info">
<div class="icon-<?=($param3 == 'pdf' ? 'pdf' : 'document')?>"></div>
<p>
<?php echo $param4;?>
</p>
</div>
<div class="col-md-8 new-file">
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<input type="text" class="form-control" name="tags" data-validate="required" data-message-required="Field is required" placeholder="File tags" value="" autofocus>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<input type="text" class="form-control" name="name" data-validate="required" data-message-required="Field is required" placeholder="File name" value="" autofocus>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<textarea rows="5" class="form-control" name="description" data-validate="required" data-message-required="Field is required" placeholder="File description" value="" autofocus></textarea>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-7">
<button type="submit" class="btn btn-info" id="submit-button">Upload</button>
<span id="preloader-form"></span>
</div>
</div>
<?php echo form_close(); ?>
This basically creates a form which later will be submitted via Ajax.
Now I proceed to handle the file submission via jQuery for the information to be sent with the file or files that are being uploaded like so:
$(document).ready(function(e) {
$('.ajax-upload').submit(function(e) {
e.preventDefault();
var $elm = $(this);
var fd = new FormData();
for(var i = 0; i < files.length; i++) {
fd.append("file_" + i, files[i]);
}
var form_data = $(".ajax-upload").serializeArray();
$.each(form_data, function(key, input) {
fd.append(input.name, input.value);
});
var opts = {
url: $elm.attr('action'),
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
beforeSend: uValidate,
success: showResponse
};
if(fd.fake) {
opts.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
xhr.send = xhr.sendAsBinary;
return xhr;
}
opts.contentType = "multipart/form-data; boundary=" + fd.boundary;
opts.data = fd.toString();
}
jQuery.ajax(opts);
return false;
});
});
Basically the form default action is overwritten and the files that were submitted on the previous code chunk for the drag and drop functionality are now appended to formData which later gets joined by the form data that was on the form I submit. Then the formData is sent via an AJAX call.
Now the controller looks like this, it handles the AJAX call and then executes the File Upload method on the model like so:
function file($param1 = '', $param2 = '', $param3 = 0) {
if ($this->session->userdata('client_login') != 1) {
$this->session->set_userdata('last_page', current_url());
redirect(base_url(), 'refresh');
}
if ($param1 == 'create')
$this->crud_model->create_file($param2);
if ($param1 == 'edit')
$this->crud_model->update_file($param2);
if ($param1 == 'delete')
$this->crud_model->delete_file($param2, $param3);
$page_data['page_name'] = 'files';
$page_data['page_title'] = 'Files List';
$page_data['folder_id'] = $param3;
$this->load->view('backend/index', $page_data);
}
Here is the model method:
function create_file($folder_id) {
$data['name'] = $this->input->post('name');
$data['tags'] = $this->input->post('tags');
$data['description'] = $this->input->post('description');
$data['type'] = 'file';
$data['folder_id'] = $folder_id;
$data['client_id'] = $this->session->userdata('login_user_id');
$config['upload_path'] = 'uploads/tmp/';
$config['allowed_types'] = '*';
$config['max_size'] = '100';
$this->load->library('upload');
$this->upload->initialize($config);
var_dump($_FILES);
die();
foreach($_FILES as $field => $file)
{
//var_dump($_FILES); die();
// No problems with the file
if($file['error'] == 0)
{
// So lets upload
if ($this->upload->do_upload($field))
{
$data = $this->upload->data();
echo $data['full_path'];
}
else
{
$errors = $this->upload->display_errors();
var_dump($errors);
}
}
}
$this->db->insert('client_files' , $data);
}
So basically what happens is that the $_FILES array is empty, and the file doesn't get uploaded.
The "Request Payload" as viewed on Chrome's Developer Tools looks like this:
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="file_0"
[object FileList]
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="tags"
bsd
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="name"
asd
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="description"
asd
And the response I get from the var_dump() on the model is the following:
array(0) {
}
I have tried the solution on this question: Sending multipart/formdata with jQuery.ajax But no luck so far.
Any idea on what am I doing wrong and how to fix this issue? Thanks.
The problem here is that I'm sending the array of files instead of the single files on the AJAX call, specifically in this part of the code:
for(var i = 0; i < files.length; i++) {
fd.append("file_" + i, files[i]);
}
The solution was to append file by file to the formData instead of the array of files, something like this:
for(var i = 0; i < files[0].length; i++) {
fd.append("file_" + i, files[i]);
}
This will append every single file of the files array instead of the array of files itself and it solves the problem.
In conclusion I was sending the array of files instead of the single files, the clue to this was the [object FileList] that the request was showing instead of the files information, which now makes a request like this:
Content-Disposition: form-data; name="file"; filename="exfile.pdf"
Content-Type: application/pdf

How to encode a local image as a multipart/form-data to post to Facebook

I am trying to post a media to Facebook's page managed my me using the FB.api("/{page_id}/photos") from JavaScript sdk. But I am unable to do so successfully.
How do I encode a local image file as a proper multipart/form-data that can be posted to Facebook.
function onChangeMediaReader() {
var file = document.getElementById('post-media').files[0];
reader = new FileReader();
reader.onload = function() {
// displays the selected image in canvas.
document.getElementById('post-media-src').src = reader.result;
document.getElementById('media-container').style.display = "block";
// form-data of the selected image for source param.
formData = new FormData();
formData.append("source", reader.result);
}
if (file) {
reader.readAsDataURL(file);
}
}
function publishPost() {
params.access_token = page_access_token;
params.message = document.getElementById('post-message').innerHTML;
if (formData) {
params.source = formData;
}
FB.getLoginStatus(function(response) {
FB.api(
'/' + page_id + '/photos',
"POST",
params,
function(response) {
console.log(response);
});
});
}
<form id="image-data" method="post" enctype="multipart/form-data">
<input type="file" name="source" id="post-media" accept="image/*" onchange="onChangeMediaReader();" />
<label for="post-media">Upload media</label>
<br />
<br />
</form>
<button id="publish-post" onclick="publishPost();">Submit</button>
Response message
"(#324) Requires upload file",
"type: "OAuthException"

Upload image using javascript

I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?
The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.
This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});
$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});

Categories

Resources