I want do decompress images in JavaScript. I have compressed the images with C# using gzip. How do I decompress gzipped data in JavaScript?
C# code
public static byte[] Compress(byte[] raw)
{
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
{
gzip.Write(raw, 0, raw.Length);
}
return memory.ToArray();
}
}
First of all you have to close the GZipStream when you are done with it.
public static byte[] Compress(byte[] raw)
{
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
{
gzip.Write(raw, 0, raw.Length);
gzip.Close();
}
return memory.ToArray();
}
}
You can use pako for decompressing in javascript.
var base64Data = "COMPRESSED_BASE64_GZIP";
var compressData = atob(base64Data);
compressData = compressData.split('').map(function (e) {
return e.charCodeAt(0);
});
var originalText = pako.ungzip(compressData, {to:"string"});
Related
I've the following code that returns an image in C# Web API. So far so good but I can't map it to an image.
[HttpPost]
[Route("GetImage")]
[ValidateAntiForgeryToken]
public FileResult GetImage(string name)
{
if (string.IsNullOrEmpty(name)) {
return File("imgs/nodisponible.jpg", "image/jpg");
}
var imagen = REST.GetImage(name);
return new FileContentResult(imagen, "image/jpeg");
}
So on the javascript side I made:
getimage(word: any): Observable<any> {
return this.http.post<ArrayBuffer>(this.baseUrl + 'library/getimage', word, {
headers: this.headers,
withCredentials: true,
});
}
and then to show the image:
const iname = JSON.stringify(this.consultadetalle?.cover_url);
this.dataService.getimage(iname).subscribe((responses) => {
$('#imagencover').attr('src', "data:image/png;base64," + responses);
});
but the console says:
Http failure during parsing for
https://localhost:44476/library/getimage"
How can I solve this?
Update:
As I said, I'm using Web API, I don't have the view in C#, only javascript with angular. In C# I've only the controllers.
You may need to convert the file to bytes first. I successfully used this, in a project similar to yours, to convert the image file to a byte array.
public static byte[] ConverToBytes(HttpPostedFileBase file)
{
var length = file.InputStream.Length; //Length: 103050706
byte[] fileData = null;
using (var binaryReader = new BinaryReader(file.InputStream))
{
fileData = binaryReader.Renter code hereeadBytes(file.ContentLength);
}
return fileData;
}
after which I loaded that information into a Viewbag and converted that to Base64
var ImageBytes = ConverToBytes(ImageFromApi);
var displayImage= "data:" + imagePulled.FileType + ";base64," + Convert.ToBase64String(ImageBytes);
ViewBag.FileBytes = displayImage;
then displayed it in a view using this.
<object data="#ViewBag.FileBytes" id="imageDisplayFrame" style="width:100%; min-height:600px; border:1px solid lightgrey; object-fit:contain;" #zoom="200" frameBorder="1" type="#ViewBag.FileType" />
I am trying to decrypt the string in JavaScript which is encrypted by using AES 256 algorithm in a C# application. The code of encryption and decryption is as below
I am able to decrypt the string in a C# application. I used the below code to decrypt the string JavaScript but I am not able to decrypt
public string Encrypt(string content)
{
if (string.IsNullOrEmpty(content))
{
throw new ArgumentNullException("content");
}
byte[] encryptedData = null;
try
{
using (AesCryptoServiceProvider aesMod = new AesCryptoServiceProvider())
{
//Set the key manullay to predefined values
aesMod.Key = m_Key;
aesMod.IV = m_IV;
ICryptoTransform encryptor = aesMod.CreateEncryptor(aesMod.Key, aesMod.IV);
// Create the streams used for encryption.
using (MemoryStream memstreamEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(memstreamEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Writing data to the stream.
swEncrypt.Write(content);
}
encryptedData = memstreamEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encryptedData);
}
catch (Exception ex)
{
throw new Exception("Exception in Encrypting .", ex);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<script>
function decryptMessage(encryptedMessage = '', secretkey = ''){
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(encryptedMessage)
});
var decrypted = CryptoJS.AES.decrypt(cipherParams, secretkey);
var decryptedMessage = decrypted.toString(CryptoJS.enc.Utf8);
return decryptedMessage;
}
</script>
The problem could be that the strings in C# are encoded in UTF-16
Try to change the encoding in the JavaScript code, if possible.
I can't get it to work to download an excel file that was created by closedxml through web API.
If I save the file on the server it looks good, but as soon as I put it in a stream and return it to the web api, then only a corrupt file is recieved in the browser.
As suggested on several posts I use httpResponseMessage, but also in the browser the filename in the header never arrives.
We are using:
"Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net461
"ClosedXML" version="0.88.0" targetFramework="net461"
WebAPI Code:
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Parcel List");
MemoryStream fs = new MemoryStream();
wb.SaveAs(fs);
fs.Position = 0;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(fs.GetBuffer());
result.Content.Headers.ContentLength = fs.Length;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "List" + "_" + DateTime.Now.ToShortDateString() + ".xlsx"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
Here the javascript code:
context.$http.post(config.get_API_URL() + 'api_call', excel_list,
{responseType: 'application/octet-stream'})
.then(
success_function,
error_function)
}
success_function:
function(response) {
var headers = response.headers;
var blob = new Blob([response.body],
{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'},
);
window.open(window.URL.createObjectURL(blob));
}
I could successfully download a workbook with this code now:
using ClosedXML.Excel;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace ClosedXML.Extensions.WebApi.Controllers
{
public class ValuesController : ApiController
{
public IHttpActionResult Get(int id)
{
return new TestFileActionResult(id);
}
}
public class TestFileActionResult : IHttpActionResult
{
public TestFileActionResult(int fileId)
{
this.FileId = fileId;
}
public int FileId { get; private set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = null;
var ms = new MemoryStream();
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
ws.FirstCell().Value = this.FileId;
wb.SaveAs(ms);
ms.Seek(0, SeekOrigin.Begin);
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(ms);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "test.xlsx";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentLength = ms.Length;
ms.Seek(0, SeekOrigin.Begin);
}
return Task.FromResult(response);
}
}
}
Have a look at the Mvc extension package at https://www.nuget.org/packages/ClosedXML.Extensions.Mvc/
PS: I've been told I have to disclaim this everytime. I'm the maintainer of ClosedXML and ClosedXML.Extensions.Mvc.
The problem seems to be that the response type for the web api call has to be {responseType: 'arraybuffer'} instead of {responseType: 'application/octet-stream'}
context.$http.post('api-url', excel_list,
{responseType: 'arraybuffer'})
.then(
success_function,
error_function)
}
Thanks anyhow for your quick help
I am trying to convert an image to base64 to upload it on sharepoint site but it is throwing 400:bad request error. when i checked properly then i found out that the base64 i am sending is endcoded by javascript and it is different than what is expected by sharepoint. I have attached 2 images here describing the difference. Can anyone help me to get the proper encoded data using javascript ?
javascript encoded base64
c# encoded base64
var files = $("#myfile").get(0).files;
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function () {
console.log(reader.result);
}
Could try : reader.result.split("base64,")[1]
Removes the "base64," start of the string.
Please try this , i am using this in my project , its working for me
if (file.ContentType.Contains("image"))
{
string theFileName = Path.GetFileName(file.FileName);
byte[] thePictureAsBytes = new byte[file.ContentLength];
using (BinaryReader theReader = new BinaryReader(file.InputStream))
{
thePictureAsBytes = theReader.ReadBytes(file.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);
}
"thePictureDataAsString " variable got Base64 string
.........................................................................
i am getting file like this in my project
public ActionResult SaveMake(string inputMakeName, HttpPostedFileBase file)
{
MakeModel objMakeModel = new MakeModel();
if (file.ContentType.Contains("image"))
{
string theFileName = Path.GetFileName(file.FileName);
byte[] thePictureAsBytes = new byte[file.ContentLength];
using (BinaryReader theReader = new BinaryReader(file.InputStream))
{
thePictureAsBytes = theReader.ReadBytes(file.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);
objMakeModel.ImageBase64 = thePictureDataAsString;
objMakeModel.Make1 = inputMakeName;
}
string response = _apiHelper.ConvertIntoReturnStringPostRequest<MakeModel>(objMakeModel, "api/Transaction/SaveMakes/");
// string response = _apiHelper.SaveMake(objMakeModel, "api/Transaction/SaveMakes/");
return RedirectToAction("AddVehicleMaintenance");
}
I am working on classic ASP with WinCE OS. I want to upload a file from WinCE and Save in the local machine. Please share the necessary JScript function for file upload which i can put it in a include file. Thank you.
Better way is to use any JavaScript library.. like jQuery..
Here are the file upload examples..
http://pixelcone.com/jquery/ajax-file-upload-script/
How can I upload files asynchronously?
Cheers :)
I have no information about asp classic but I have used Asp.net and you can use asp to receive file in order to upload file from wince use can develop app using c# here is an example.
Its client WinCE Application Code Function Upload(string Path, String FileName) takes File Path and File Name as Input and Post it to web page
#region Upload
public bool Upload(string FilePath, string FileName)
{
string Url = "HTTP://test.mtsonweb.com/fileupload.ashx"; // Change it to your page name
string BytesConfirmedReceived = "";
int BytesSent = 0;
bool Ret = false;
ASCIIEncoding encoding = new ASCIIEncoding();
try
{
if (File.Exists(FilePath +"\\"+ FileName) == false) { return true; }
//FileInfo oInfo = new FileInfo(FilePath + "\\" + FileName);
//BytesSent = Convert.ToInt32(oInfo.Length.ToString());
Url += "?myfile=" + FileName.Trim();
FileStream fr = new FileStream(FilePath + "\\" + FileName, FileMode.Open);
BinaryReader r = new BinaryReader(fr);
byte[] FileContents = r.ReadBytes((int)fr.Length);
BytesSent = FileContents.Length;
r.Close();
fr.Close();
WebRequest oRequest = WebRequest.Create(Url);
oRequest.Method = "POST";
oRequest.Timeout = 15000;
oRequest.ContentLength = FileContents.Length;
Stream oStream = oRequest.GetRequestStream();
BinaryWriter oWriter = new BinaryWriter(oStream);
oWriter.Write(FileContents);
oWriter.Close();
oStream.Close();
WebResponse oResponse = oRequest.GetResponse();
BytesConfirmedReceived = new StreamReader(oResponse.GetResponseStream(),
Encoding.Default).ReadToEnd();
oResponse.Close();
if (BytesSent.ToString() == BytesConfirmedReceived.Trim())
{
Ret = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return Ret;
}
#endregion
Now of you page you can handle file uploaded using script whatever you want, I have used asp.net with c# as back-end and below is the source of page:
<%# WebHandler Language="C#" Class="FileUpload" %>
using System;
using System.Xml;
using System.Data;
using System.Web;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
public class FileUpload : IHttpHandler
{
public void ProcessRequest(HttpContext oContext)
{
int BytesSent = 0;
//string LocalPath = #"C:\Inetpub\wwwroot\";
string MyFile = "";
try
{
MyFile = oContext.Request["myfile"].ToString().Trim();
MyFile = HttpContext.Current.Server.MapPath("~/Demo/Files/" +
ASCIIEncoding encoding = new ASCIIEncoding();
BytesSent = oContext.Request.TotalBytes;
Class1 obj = Class1.GetInstance();
obj.FileName = MyFile;
obj.FileLength = BytesSent;
byte[] InComingBinaryArray =
oContext.Request.BinaryRead(oContext.Request.TotalBytes);
obj.Data = InComingBinaryArray;
if (File.Exists(MyFile) == true)
{
File.Delete(MyFile);
}
FileStream fs = new FileStream(MyFile, FileMode.CreateNew);
BinaryWriter w = new BinaryWriter(fs);
w.Write(InComingBinaryArray);
w.Close();
fs.Close();
FileInfo oInfo = new FileInfo(MyFile);
long a = (long)BytesSent;
oContext.Response.Write(oInfo.Length.ToString());
}
catch (Exception err) { oContext.Response.Write(err.Message); }
}
public bool IsReusable { get { return true; } }
}