I'm storing my PDF files into my SQL database using C# and using BLOB(long) as my SQL datatype.
C# code:
Convert PDF to bytes
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, System.Convert.ToInt32(fs.Length));
Storing bytes into the database
string query = "INSERT INTO invoices (data, dateTime, invoiceNo, ni) VALUES (#d, #dt, #in, #ni)";
var cmd = new MySqlCommand(query, dbCon.Connection);
cmd.Parameters.AddWithValue("#d", bytes);
cmd.Parameters.AddWithValue("#dt", dateTime);
cmd.Parameters.AddWithValue("#in", invoiceNo);
cmd.Parameters.AddWithValue("#ni", ni);
try
{
cmd.ExecuteNonQuery();
Database table structure (Using longblob):
Now, that is all done from the client application and there are multiple records, on the web side, i'm trying to pull that blob data from the database and convert it back to PDF and download it. It all works great apart from the PDF is blank even though there is an average of 170kb per PDF.
Web side:
I'm getting the blob data from the database and trying to convert it into a PDF file using this JavaScript function:
function convertInvoiceBlob(fileName, resData) {
var newBlob = new Blob([resData], {type: "application/pdf"});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
const data = window.URL.createObjectURL(newBlob);
var link = document.createElement("a");
link.href = data;
link.download= fileName;
link.click();
setTimeout(function(){
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}
However I'm receiving a blank PDF. I'm not quite sure which part I have mistakes at, whether its storing it into the database incorrectly or receiving the data and converting it incorrectly.
Related
I have following problem. I am saving image to local storage by converting it to string base 64 format via file reader.readAsDataUrl. it is stored properly. Now I want to send that image to the server. I am using fetch to fetch url and then blobing it to form a file. when i console.log i get same file as I got before converting to base 64 exept name is different. but when sending to the server that file object it returns unprocecable content. The image must be an image.
fr.readAsDataURL(value);
fr.addEventListener("load",() => {
// assigning freader value to state and refferencing it to `newVal`
// saving only happens inside `this` eventListener
try{
const newVal = generalInfo[iName][0] = fr.result;
// console.log(newVal)
setGeneralInfo({...generalInfo,newVal});
localStorage.setItem("generalP", JSON.stringify(generalInfo));
}
catch(e){
alert("photo sized more than 1mb cannot be uploaded");
// get back to current state values using LC
getFromLC();
}
})
and here is retrieving from local storage and turning it into file
const getSendingData = async () => {
//strip off the data uri prefix
// getting base64 string as data url
const response = await fetch(generalInfo.photo[0]);
const blob = await response.blob();
const file = new File([blob],'image',{type: blob.type});
// continue from here
console.log(file)
}
I am implementing a websocket server to transfer files to clients, that is, I send the bytes of the file in parts from the server to the client, and from the client I join the byte fragments and create the file with its extension.
My problem is that the string apparently can only store and concatenate only up to 500mb approx, which would limit the generation of larger files such as 1gb or greater since it freezes.
Is there any way to buffer that large amount of data and be able to download it as files?
I have searched and found about StreamSaver.js but I have not been able to implement it with the internet examples to create that giant data buffer. Thanks!
I leave a sample of my code to pass from a hex string to files.
function CreateFile(DataHex, FileName) {
var binary = new Array();
for (var i=0; i<DataHex.length/2; i++) {
var h = DataHex.substr(i*2, 2);
binary[i] = parseInt(h,16);
}
var byteArray = new Uint8Array(binary);
var filecomp = window.document.createElement('a');
filecomp.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/octet-stream' }));
filecomp.download = FileName;
filecomp.click();
window.URL.revokeObjectURL(filecomp.href);
}
I've seen SO questions similar to my use case w/ angular and other server side platforms but not for pure javascript.
I have an app where I do a $.ajax and do a get call to an API, which returns a previously converted excel file (excel to base64); I need to re-convert this base64 data back into it's original form - i.e. into Excel file. I tried retracing the steps I took to convert the excel into base64, reversing some of them, but I'm not able to generate the original file. An excel file IS being generated, but it still has base64 data and therefore opens w/ errors and in a corrupted state.
Has anyone else successfully done this?
Below is my code and fiddle link: (I didn't add the base64 json data (responseData) here since it's large, but it's on the fiddle)
var bindata = window.atob(responseData);
function DownloadExcel() {
window.location.href = "data:application/vnd.ms-excel;base64, bindata"
}
var blob = new Blob([responseData], {type: 'application/vnd.ms-excel'});
if (window.navigator && window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob);
}
else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
jsfiddle link: https://jsfiddle.net/damon_matt/2ofz6xrd/
I am struggling to convert my canvas URL to a blob format, specifically in PNG format. The DataURL is generating quite perfectly when I tested it without the conversion code, the problem comes in when trying to convert it to Blob. I am using an html button that triggers the JavaScript function with the ID buttonTextArea.
I need the Blob file to be linked to my APEX page item, which I use the $s('P9_IMAGE_CODE', Blob) format, which also works when I tested it using text only. Once the page is processed, that item will be sent into a blob column within my table.
Here is my code:
$("#buttonTextArea").click(function(dataURL) {
var BASE64_MARKER = ';base64,';
var canvas = document.getElementById('myCanvas');
var dataURL = canvas.toDataURL();
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});
document.getElementById("textArea").value = dataUrl;
$s('P9_IMAGE_CODE', Blob); --P9_IMAGE_CODE IS THE ITEM ON MY PAGE
});
I have been trying examples from :
https://github.com/blueimp/JavaScript-Canvas-to-Blob/blob/master/README.md
and
https://code.google.com/p/chromium/issues/detail?id=67587
Thank you in advance.
As Jeffrey pointed out, the javasscript "Blob" is not the same as the Oracle BLOB datatype.
The toDataURL function is already returning a base64 encoded string, so what you'd need to do is to save that string and then after submit convert it into a real blob.
Sending it to the database may be a bit of an issue since there is a limit of 32k bytes on an item's content. This means you'll likely have to send the string in chunks to the database. This is then not a VARCHAR2 (which also has a limit of 32k) but a CLOB.
As Wesley points out, there are some workarounds for that. The blog he linked to is one such example. There is also a plugin to facilitate the handling of clobs in apex.
Once you get the base64 string to the database, you'll have to convert it to a real blob. There is no built-in to quickly do this, but once again this is something several people have already solved.
A script is provided here by Tim Hall to convert a CLOB to a BLOB.
So:
In the browser, get the dataURL, which is a base64 encoded string
send it in chunks to the database, where it'll be a CLOB
after everything has been sent, convert the CLOB to a BLOB and save
it in your table
I'm trying to store images in DB2 Database as BLOB contents. I used JS to convert the image content to base64.
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textAreaFileContents = document.getElementById
(
"textAreaFileContents"
);
textAreaFileContents.innerHTML = fileLoadedEvent.target.result;
var ImgContent = fileLoadedEvent.target.result;
$("#IMAGE").attr("src",ImgContent);
};
fileReader.readAsDataURL(fileToLoad);
}
}
Now I need to convert this base64 content to binary and store them to my DB2 Database. Is there any way to do this in JavaScript?
And how to fetch this data from the database and display it on my mobile app using Adapters. ?
Why do you not simply store the image as encoded to base64 in database? I think this would be better in your scenario...
You receive an image
You use some library to handle the encoding to base64
Review this question: Base64 encoding and decoding in client-side Javascript
You store the image-now a string, in the database
When you need to display the image in the app, fetch the contents and decode it (see step 2)