At work we are trying to upload files from a web page to a web service using html 5/javascript in the browser end and C# in the web service. But have some trouble with encoding of some sort.
As for the javascript we get the file's binary data with help from a FileReader.
var file = ... // gets the file from an input
var fileReader = new FileReader();
fileReader.onload = dataRecieved;
fileReader.readAsBinaryString(file);
function dataRecieved() {
// Here we do a normal jquery ajax post with the file data (fileReader.result).
}
Wy we are posting the data manually and not with help from XmlHttpRequest (or similar) is for easier overall posting to our web service from different parts of the web page (it's wrapped in a function). But that doesn't seem to be the problem.
The code in the Web Service looks like this
[WebMethod]
public string SaveFileValueFieldValue(string value)
{
System.Text.UnicodeEncoding encoder = new UnicodeEncoding();
byte[] bytes = encoder.GetBytes(value);
// Saves file from bytes here...
}
All works well, and the data seems to be normal, but when trying to open a file (an image as example) it cannot be opened. Very basic text files seems to turn out okay. But if I upload a "binary" file like an image and then open both the original and the uploaded version in a normal text editor as notepad to see what differs, it seems to be wrong with only a few "invisible" characters and something that displays as a new line a few bytes in from from the start.
So basicly, the file seems to encode just a few bytes wrong somewhere in the conversions.
I've also tried to create an int array in javascript from the data, and then again transformed to a byte[] in the web service, with the exact same problem. If I try to convert with anything else than unicode (like UTF-8), the data turns out completly different from the original, so I think om on the right track here, but with something slightly wrong.
The request itself is text, so binary data is lost if you send the wrong enc-type.
What you can do is encode the binary to base64 and decode it on the other side.
To change the enc-type to multi-part/mixed and set boundaries (just like an e-mail or something) you'd have to assemble the request yourself.
Related
I have an application where you can upload and view images and i am trying to implement pdf's aswell without using a free trial or an expensive package.
The application works by:
uploading file
decoding file (IFileFormat) to bytes
putting the bytes into a database
taking the bytes from the database
converting bytes to base64
creating a link and viewing the image(works). or using pdf.js to paint the pdf as an image on canvas
the controller code:
string imageDataBytes = Convert.ToBase64String(image.FileData);
ViewBag.basesixtyfour = imageDataBytes;
Console.WriteLine(imageDatabytes);
the script code:
<script>
console.log('#ViewBag.basesixtyfour');
</script>
in short the console writeline gives me a string value that is 275,500 bytes.
the console.log gives me a string value that is 308,050 bytes.
I have tried using a model to carry the string aswell but the same problem arises.
So the question is, why does this happen? are there any workarounds?
Figured it out after a while.
Had to serialize for json and then deserialize using Newsoft.Json
controller
ViewBag.story = JsonConvert.SerializeObject(imageDataBytes);
View
var pdfData = atob('#Html.Raw(JsonConvert.DeserializeObject(ViewBag.story))');
I am using a library to recieve attachments (image) from salesforce using OAuth and a proxy. Without the library (and the proxy) I am able to the same using XHR, but I have to use the library because I need the proxy.
In chrome debugger I can see image is downloaded fine, but I can't get it to work in my code. Data looks like:
So far methods I have tried:
btoa(unescape(encodeURIComponent(file.body)));- produces a base64 that does not work. decoding it using online tools gives me back the same string.
escape(file.body) - using this as base64 also does not work.
Converting to a blob.
var blob = new Blob([file.body], {type : "image/png"});
urlCreator.createObjectURL(blob);
The url it points to displays nothing, and if I remove {type : "image/png"} the url points to a page displaying same binary string.
Long story short this looks like someone read the image with readAsText() which mangles ("interprets") binary into utf8, instead of utf16. You need to get the server to return the data in arraybuffer or blob format ideally, or even base64, these preserve binary.
Long version with snippet. (those question marks symbols in the snippet show the lost information, compare it to the binary where they are not question marks in utf16):
https://stackoverflow.com/a/56523118/2962797
I would create an <img /> element, equal its src attribute to the image data you received. Now you have the image.
If you want to extract it or convert it to PNG, I would apply this another answer process.
I want to use an API to compress images. It says the input can as well be a buffer (string with binary), for example:
$sourceData = file_get_contents("unoptimized.jpg");
$resultData = \Tinify\fromBuffer($sourceData)->toBuffer();
In my understanding, they use file_get_contents to create that buffer from a file.
In my case, I already got an canvas image using a React application. To make the API call, I create a data URI, using .toDataURL() looking something like this:
data:image/png;base64,iVBORw0KGgoAAAANSUh... // lots of letters
So can I just use this data URI instead of file_get_contents, because both commands actually do the same in different languages, or is there a difference? Like:
$sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUh...'
\Tinify\fromBuffer($sourceData)->toBuffer();
API Reference: https://tinypng.com/developers/reference/php
file_get_contents returns the content of a file as string, and that string exactly represents the content of the file.
.toDataURL() gives you a data url. The data:image/png;base64, part tells that the following data represents a png and that the data is base64 encoded.
To get the same data representation as you get with file_get_content you would need to decode the iVBORw0KGgoAAAANSUh...
So yes, both give you the content of a file, but they don't do that in the same way.
To toBlob on the other hand will return a Buffer containing the data in the same representation as file_get_contents would do.
Assuming you have a PNG file named input.png, the following two pieces of code produce the same result:
Read the image data from the PNG file:
$sourceData = file_get_contents('input.png');
Read the image data from a data: URL generated from the PNG file:
// Generate the 'data:' URL
$url = 'data:image/png;base64,'.base64_encode(file_get_contents('input.png'));
// Read the image data from the 'data:' URL
$sourceData = file_get_contents($url);
The second piece of code works only if fopen wrappers are enabled on the server where the file_get_contents() is executed.
It doesn't make much sense to use the second fragment of code in a single script (because it does a redundant encoding and decoding) but it makes a lot of sense if the encoding and restoring (decoding) happen in different scripts.
They can be part of the same application (the script that encodes the data stores it in the database, the other script loads from the database, restores the image data and uses it) or the decoding could happen in a remote application that sends the data URL over the Internet to be decoded and used by a different application.
I get data from a server of the .pptx file in base64 encoding now i would like to get the text that is present inside the base64 data.
Is there any third party java script library to do this especially scanning in base64 code rather than taking the file path and i would like insert these strings into a power point using office js.
Client side would be preferred.
thanks
Seems that what you need is a JavaScript decoder for base64 files, there are many projects in Github Doing this, for instance here is one https://github.com/mathiasbynens/base64.
That said, I am not sure about your scenario, and what types of files are been base64-encoded. Base64 at the end of the day is a text "representation" of usually a binary file, like an image or a compressed zip file. I wonder if once you decode it you will get what you expect. And if you are expecting text, i wonder why your service is even encoding it like this.
Anyways... once you have whatever text you want to insert, you can use the setSelectedDataAsync method of our Office.js in PPT to write it in your presentation's active selection. https://dev.office.com/reference/add-ins/shared/document.setselecteddataasync
Background:
I'm developing an HTML5 webapp for my company which is basically a Rich Text Editor (similar to Google Docs) that stores information in a database.
We are using CKEditor 3 as richtext editor and Jquery to acomplish this.
We've chosen Google's Chrome as the preferred browser.
Our app is currently in alpha testing period, having a group of 18 tester (which are the same ones that will use the app). These people is heterogeneous, but almost all of them of them have basic computer skills, mostly limited to MS Word and MS Excel.
.
Problem:
Most of our users still use word to elaborate the document, mainly due to its capacity of generating rich flowcharts. When they copy/paste the generated content to Chrome, images are pasted as link to a local file (auto generated by the OS, in a users/*/temp folder). This means the server can't access these files and the resulting documents (generated PDFs) don't contain the images.
.
Question
How can I force pasted images to be encoded in base64, similiar to what happens in Firefox?
.
Notes
If it's possible to "upload" to server an image referenced as src="file://c:\something", that would solve my problem as I can base64 encode that image later.
We can't switch to firefox since it doesn't fully solve our problem (if an image is "pasted" alongside with text, firefox doesn't base64 encode it) and raises other issues such as an horizontal scrollbar appearing when the text is too long to fit in the textarea.
Yes and no I believe.
It is possible to intercept the paste event and fetch the pasted image as a file, then use FileReader to read the file as a Data URI (base 64 encoded PNG).
However, Word seems to send a reference to a local file, which generates a security exception (at least on Chrome) because of a cross-domain request (http://... and file:///...). As far as I'm concerned there is no way to get the actual contents of such local files, and the contents are not sent as clipboard data itself.
If you copy a "pure" image (e.g. out of Paint), you can get the base 64 encoded data as follows: http://jsfiddle.net/pimvdb/zTAuR/. Or append the image as a base 64 encoded PNG in the div: http://jsfiddle.net/pimvdb/zTAuR/2/.
div.onpaste = function(e) {
var data = e.clipboardData.items[0].getAsFile();
var fr = new FileReader;
fr.onloadend = function() {
alert(fr.result.substring(0, 100)); // fr.result is all data
};
fr.readAsDataURL(data);
};