I have a BLOB URL that has the pdf file with the content:
blob:http://localhost/468479b7-7db1-4e35-ab35-acf9ff0739f8
Using the filereader i convert it to base64:
var myReader = new FileReader();
var blob = new Blob([v.src], {type: "application/pdf"});
myReader.readAsDataURL(blob);
myReader.onload = function(event) {
result = event.target.result;
console.log(result);
console.log(v.src);
};
The result is:
data:application/pdf;base64,YmxvYjpodHRwOi8vbG9jYWxob3N0LzQ2ODQ3OWI3LTdkYjEtNGUzNS1hYjM1LWFjZjlmZjA3MzlmOA==
Now can i get the pdf content from the encoded url?
If not, what are my options?
Extract the content part. Decode and save into a file.
$data = explode(';',"data:application/pdf;base64,YmxvYjpodHRwOi8vbG9jYWxob3N0LzQ2ODQ3OWI3LTdkYjEtNGUzNS1hYjM1LWFjZjlmZjA3MzlmOA");
$encoded = explode(',',$data[1]);
file_put_contents("test.pdf",base64_decode($encoded[1]));
Related
I'd like to compare the hashed version of the file against the data stored in the database, so I can abort duplicate uploads.
Being quite "new" to the subjects of hashing and the FileReader API, I'm finding the process a bit confusing.
I am using the frontend library SparkMD5.js
Test n1 compare two strings:
// frontend
$.post(url, {sparkMD5('random text')})
// backend
$input->hash == md5('random text') // outputs true
Test n2 - inside fineuploader onSubmit event handler
// frontend
var file = this.getFile(id);
var reader = new FileReader();
//
reader.onload = function(e) {
var data = reader.result;
var hexHash = SparkMD5.hash(data);
console.log(hexHash);
}
var res = reader.readAsDataURL(file); // or reader.readAsBinaryString(file)
......
//backend
$file = Input::file('qqfile');
$hash = md5(file ) // or md5_file(file )
$hash == $input->hexHash // outputs false
My questions:
1) Why is the result of md5($file) == md5_file($file) \\ false ?
2) What's the correct way of reading a file readAsDataURL or readAsBinaryString ?
3) Is there a way to read and hash the result of fineuploader's getFile(id) which returns File or Blob, without using filereader api?
Answers to the above questions may be considered broad and out of scope of my immediate problem, but i'd like to understand the subject as best as possible.
Thanks.
Input::file() returns an instance of Illuminate\Http\UplaodedFile, so to get the hash of its contents you can do the following:
// md5_file takes in the file path as argument
$hash = md5_file(Input::file('yourfile')->path());
readAsDataURL() is much safer because the file is encoded as base64. Just make sure that the server is aware of the encoding, meaning remove the first characters up to the comma then decode the rest as base64. More information here: fileReader.readAsBinaryString to upload files
According to this you still have to use filereader: How to include Content-MD5 header in FineUploader Azure request?.
Thanks to #alio f I was able to come up with a solution. Here's the code.
frontend
var t = this;
var reader = new FileReader();
var file = this.getFile(id);
reader.addEventListener("load", function () {
var base64result = reader.result.split(',')[1]; // only get base64 string
var hash = SparkMD5.hash(base64result);
}, false);
var data = reader.readAsDataURL(file);
Refer to FineUploader docs for the onSubmit handler.
backend
$this->file = Input::file('qqfile');
$base64 = base64_encode(file_get_contents($this->file));
$hash = md5($base64);
Comparing frontend's md5 and backend's md5 now returns true
I would like to be able to display an image on the file script.php with the help of data transmitted by this code (Actionscript)
I get data by the POST method but I do not know what to do with it.
header('Content-Type: image/jpeg');
I don't know what to do with $_POST
public function onTakePhoto(param1:Event) : void
{
var _loc1_:Bitmap = new Bitmap(new BitmapData(680,440));
var _loc2_:Matrix = new Matrix();
_loc2_.translate(-290,-150);
_loc2_.scale(2,2);
_loc1_.bitmapData.draw(DisplayObject(something),_loc2_);
var _loc3_:ByteArray = new ByteArray();
_loc1_.bitmapData.encode(_loc1_.bitmapData.rect,new JPEGEncoderOptions(),_loc3_);
var _loc4_:URLRequest = new URLRequest("script.php");
_loc4_.method = URLRequestMethod.POST;
_loc4_.data = _loc3_;
navigateToURL(_loc4_,"_blank");
_loc1_.bitmapData.dispose();
}
You can fetch the $_POST data like this:
$image_data = file_get_contents("php://input");
//proceed by perhaps saving the image to the server:
file_put_contents('path/to/save/image.jpg',$image_data);
I need to upload image using ajax. Elaborating my point:
I need to pass my image data to a PHP page and check the type, size, name and all other attributes of the file. If all attributes matches, then only I need to transfer the file. Problem here is passing of data should be done in JSON(AJAX) format only. One more important thing is that I don't have to convert it to base64.
If you can help me in this, You are most welcome.
Thanks in advance.
The idea in SO is to work on the OP current code. I mean, we are not here to make all the job, because it should have a price. Anyway, here is a workaround for your issue:
Convert your image to base64 using javascript. This useful method works like a charm:
// Code taken from MatthewCrumley (http://stackoverflow.com/a/934925/298479)
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to guess the
// original format, but be aware the using "image/jpg" will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
Then just pass the returned string as base64 through ajax:
$.ajax({
url: 'path/to/your/script.php',
type: 'post',
data: { paramName: imagedata } // the returned data from above js method,
/*...*/
});
And, in PHP side, just return the string to an image file:
// Code taken from Austin Brunkhorst (http://stackoverflow.com/a/15153931/3648578)
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}
I'm trying to code my own php uploader so I can learn and understand how it all works. Trying not to use any libraries/plugins/API's. So basically I have the javascript stuff doin what it's supposed to be (i hope..). Now I'm stuck on the PHP. I want it to upload and save it as img/1.png. (not using any variables just to test it...). Here are my scripts. Keeping it very simple without any error checks just to get basic uploading working. Would this work for multiple files? May somebody guide me on what my PHP file should look like just for very basic (multi)file upload? Thanks!
album_create.js
$(document).ready(function() {
$('#album_create').submit(function() {
var file = document.getElementById('album-files').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.onload = function(f) {shipOff(f);};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file, 'UTF-8');
return false;
});
});
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('album-files').files[0].name; //Should be 'picture.jpg'
console.log(fileName);
$.post('ajax/album_create.php', { data: result, name: fileName }, function(data){console.log(data);});
return false;
}
ajax/album_create.php
$data = $_POST['data'];
move_uploaded_file($data[0], 'img/1.png');
you are posting:
data: result, name: fileName
but album_create.php expecting:
$data = $_POST['data'];
$fileName = $_POST['fileName'];
$fileName = $_POST['fileName']; should be: $fileName = $_POST['name'];
Export HighChart as an image in excel file together with the other page contents like tables, text, etc. When I click the export button the whole Page content will be save as excel file via header but instead of exporting all page content to excel file it excludes the HighChart Graph. I think the solution is to export the graph as image in excel but I don't have any idea how to that. Is there anyone know how to do it or have any idea how to solve this problem?
Here is link on highcharts documentation. Thats will help u to export image and store it.
a) Documentation #1
b) Documentation #2
That will help u with PHPExcel classs API.
And finally exapmle of image paste to a sheet, using PHPExcel class: one or two;
Have more questions? See that links: one, two.
And official PHPExcel examples: here.
Good luck!
First you have to send the svgtext and the csv text ti the server via ajax.
Then do the following:
public JsonResult ExportToImage(string base64, string graphdata)
{
try
{
var base64String = base64.Remove(0, 1);
var rows = graphdata.Split('\n');
byte[] bytes = Convert.FromBase64String(base64);
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "Content\\Images\\");
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles("*.xls")
.Where(p => p.Extension == ".xls").ToArray();
foreach (FileInfo file in files)
try
{
file.Attributes = FileAttributes.Normal;
System.IO.File.Delete(file.FullName);
}
catch { }
using (Image image = Image.FromStream(new MemoryStream(bytes)))
{
image.Save(path+"output.png", ImageFormat.Jpeg); // Or Png
}
var xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];
for(var y=0; y<rows.Count();y++)
{
var row = rows[y];
var columValues = row.Split(',');
for (var x = 0; x < columValues.Count(); x++)
{
xlWorkSheet.Cells[y+20, x+1] = columValues[x];
}
}
xlWorkSheet.Shapes.AddPicture(path + "output.png", MsoTriState.msoFalse, MsoTriState.msoCTrue, 0, 0, -1, -1);
var fileName = string.Format("GraphDataExport{0}.xls", DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"));
xlWorkBook.SaveAs(path + fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
return Json(fileName);
}
catch (Exception e)
{
return Json(e.Message + Environment.NewLine + e.InnerException + Environment.NewLine + e.Data + Environment.NewLine);
}
}
Now you can do a window.location to that file