HttpHandler [Image] cannot be displayed because it contains errors - asp.net

Ok i have been working non stop on this and doing a lot of searching. I cannot get my images to display when pulling them from the database. If i try going to the handler link manually i get a message saying "The image [Image] cannot be displayed because it contains errors". I had some old images in the database from before and it first displayed those correctly. But now if i update images it will give me this error when trying to view them.
Upload code.
if (fileuploadImage.HasFile)
{
if (IsValidImage(fileuploadImage))
{
int length = fileuploadImage.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileuploadImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
if (mainImage == null)
{
ProfileImage image = new ProfileImage();
image.ImageName = txtImageName.Text;
image.ImageData = imgbyte;
image.ImageType = img.ContentType;
image.MainImage = true;
image.PersonID = personID;
if (image.CreateImage() <= 0)
{
SetError("There was an error uploading this image.");
}
}
else
{
mainImage.ImageName = txtImageName.Text;
mainImage.ImageType = img.ContentType;
mainImage.ImageData = imgbyte;
mainImage.MainImage = true;
mainImage.PersonID = personID;
if (!mainImage.UpdateImage())
{
SetError("There was an error uploading this image.");
}
}
}
else
{
SetError("Not a valid image type.");
}
Here is my image handler:
public class ImageHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
int imageid = Parser.GetInt(context.Request.QueryString["ImID"]);
ProfileImage image = new ProfileImage(Parser.GetInt(imageid));
context.Response.ContentType = image.ImageType;
context.Response.Clear();
context.Response.BinaryWrite(image.ImageData);
context.Response.End();
}
And this is how i'm calling it "~/ImageHandler.ashx?ImID=" + Parser.GetString(image.ImageID)
I'm using the data type Image in sql server to store this.
Edit:
I also found out that if i put a try catch around context.Response.end() it is erroring out saying the "Unable to evaluate the code because the native frame..."

I found my problem. I was checking the header of the actual file to make sure it was valid. Somehow that was altering the data and making it bad.

Related

Xamarin.Forms failing to use EvoHtmlToPdfclient in order to convert html string to a pdf file

I'm using Xamarin.Forms and I am trying to convert an html string to a pdf file using EvoPdfConverter, but the problem is that when I try to do so, on the line htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString()); in the code snippet below, the app just freezes and does nothing, seems like it wants to connect to the given IP, but it can't, however I don't get any errors or exceptions! not even catch!! does anybody know what I should do to resolve this issue? and here is my code for this:
public void ConvertHtmlToPfd(string htmlData)
{
ServerSocket s = new ServerSocket(0);
HtmlToPdfConverter htmlToPdfConverter = new
HtmlToPdfConverter(GetLocalIPAddress(),(uint)s.LocalPort);
htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto;
htmlToPdfConverter.PdfDocumentOptions.CompressCrossReference = true;
htmlToPdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Best;
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
}
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
}
try
{
// create the HTML to PDF converter object
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
Java.IO.File myDir = new Java.IO.File(root + "/Reports");
try
{
myDir.Mkdir();
}
catch (Exception e)
{
string message = e.Message;
}
Java.IO.File file = new Java.IO.File(myDir, filename);
if (file.Exists()) file.Delete();
htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString());
}
catch (Exception ex)
{
string message = ex.Message;
}
}
Could you try to set a base URL to ConvertHtmlToFile call as the second parameter? You passed an empty string. That helps to resolve the relative URLs found in HTML to full URLs. The converter might have delays when trying to retrieve content from invalid resources URLs.

Browser caching images from ASP.NET Handler with complex URL not working

I'm trying to cache images, which are provided using a ASP.NET Handler same code as below:
Handler
public class ResourceHandler : IHttpHandler, IRouteHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.Private);
context.Response.Cache.SetMaxAge(new TimeSpan(1, 0, 0));
RouteData routeData = HttpContext.Current.Request.RequestContext.RouteData;
string name = routeData.Values["type"].ToString();
string imagePath = "path/{type}"
FileInfo fileInfo = new FileInfo(imagePath);
if (fileInfo == null)
{
// Resource not found
context.Response.StatusCode = 404;
return;
}
string rawIfModifiedSince = context.Request.Headers.Get("If-Modified-Since");
if (string.IsNullOrEmpty(rawIfModifiedSince))
{
// Set Last Modified time
context.Response.Cache.SetLastModified(fileInfo.LastWriteTimeUtc);
}
else
{
DateTime ifModifiedSince = DateTime.Parse(rawIfModifiedSince);
// HTTP does not provide milliseconds, so remove it from the comparison
if (fileInfo.LastWriteTimeUtc.AddMilliseconds(
-fileInfo.LastWriteTimeUtc.Millisecond) == ifModifiedSince)
{
// The requested file has not changed
context.Response.StatusCode = 304;
return;
}
}
using (Stream stream = fileInfo.OpenRead())
{
byte[] buffer = new byte[32];
while (stream.Read(buffer, 0, 32) > 0)
{
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(buffer);
}
}
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return this;
}
public bool IsReusable
{
get { return true; }
}
}
}
Routes
I figure out that the route complexity was forcing the browser to always request from the server, never from the cache. (I've tried many, Chrome, Firefox, Edge)
If I register a simple route, everything works as intended:
routes.Add(new Route("image/{type}", new ResourceHandler()));
Example:
http://localhost/image/CompanyLogo/f8d8c2cc-271c-407e-9bbb-3deae1c577da_f8d8c2cc-271c-407e-9bbb-3deae1c577da_9bc61578-6c05-4532-8dce-ed2d6e28e8fc?size=normal&d=02102018061450
But Every browser refuses to get an image from cache if the url is like this:
routes.Add(new Route("image/{type}/{authenticatedUserId}/{userId}/{imageid}", new ResourceHandler()));
Example:
http://localhost/image/CompanyLogo/f8d8c2cc-271c-407e-9bbb-3deae1c577da/f8d8c2cc-271c-407e-9bbb-3deae1c577da/9bc61578-6c05-4532-8dce-ed2d6e28e8fc?size=normal&d=02102018061450
I've tried every possible header in combination, but why is the URL the issue? The simple one works, the dynamic one doesn't.
UPDATE
It works with the latest version of Firefox.

JxBrowser - Save cached image

Is there a way to save a cached image from a loaded page? I would like to be able to right click on a image and have a option to "Save image as...". I know I could extract the image url and download it but if the image changes I won't be able to get the current one displayed on the page.
Right now JxBrowser API doesn't provide functionality that allows saving images via approach you are requesting.
This feature will be implemented in one of the next JxBrowser versions. I will let you know when updated build with the feature is available for download.
YOu can try this solution:
NetworkService networkService = browser.getContext().getNetworkService();
networkService.setNetworkDelegate(new DefaultNetworkDelegate() {
#Override
public void onDataReceived(DataReceivedParams params) {
if (params.getMimeType().equals("image/png")) {
byte[] img = params.getData();
if(img!=null){
ByteArrayToImage("png",img);
System.out.println("PNG image data = " + Arrays.toString(img));
}
}
if (params.getMimeType().equals("image/jpeg") || params.getMimeType().equals("image/jpg")) {
byte[] img = params.getData();
if(img!=null){
ByteArrayToImage("jpg",img);
System.out.println("jpeg image data = " + Arrays.toString(img));
}
}
}
});
With utility image routine:
public static void ByteArrayToImage(String imageType, byte[] data) {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2;
Random rn = new Random();
int random = rn.nextInt(100) + 1;
try {
bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, imageType, new File("D://tmp//output"+random+"." + imageType) );
System.out.println("image created");
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

How to cast string to HttpFilePostedBase

Is there a way how to convert the string to HttpFilePostedBase?
I'm currently using the Ajax File upload . But the value that it return is string. But my method is requesting for HttpFilePostedBase is there a way how to cast or convert it to HttpFilePostedBase?
here's my sample method in uploading files.
public bool uploadfiles(HttpPostedFileBase filedata)
{
bool status = false;
//code for uploading goes here
return status;
}
How can i call this method if the ajax file upload is passing a string?
Are you using IE or Chrome/Firefox? cause, different browsers upload files in a different manner. IE uploads the files through Requres.Files but others use qqfile in the query string.
Take a look here on how to use valums with mvc for different browsers
EDIT: Okay then, how about this. This is an example which worked for me:
public void ControllerUploadHandler()
{
// Set the response return data type
this.Response.ContentType = "text/html";
try
{
// get just the original filename
byte[] buffer = new byte[Request.ContentLength];
if (Request.QueryString["qqfile"] != null)
{
using (BinaryReader br = new BinaryReader(this.Request.InputStream))
br.Read(buffer, 0, buffer.Length);
}
else if (Request.Files.Count > 0)
{
HttpPostedFileBase httpPostedFileBase = Request.Files[0] as HttpPostedFileBase;
using (BinaryReader br = new BinaryReader(httpPostedFileBase.InputStream))
br.Read(buffer, 0, buffer.Length);
}
else
this.Response.Write(" {'success': false }");
// return the json object as successful
this.Response.Write("{ 'success': true }");
this.Response.End();
return;
}
catch (Exception)
{
// return the json object as unsuccessful
this.Response.Write("{ 'success': false }");
this.Response.End();
}
}
You can't. You can access files posted to an aspx page via the HttpContext.Request.Files property.

Sometimes Image is not displaying for only one user

I am having ASP.NET MVC application in which i am using HTTP handler ashx file to get the image on the page . This image is uploaded by user by scanning the document.
Now my problem is for every user its displaying except one , User is reporting he is not able to see the image even though it was loaded sucessfully , when i checked the logs it shown that server got image.
No exception was logged at the server while converting image too :(
One more thing this is happening frequently , 70% times user is not able to see the image in the page. 30% time he managed to see the image ...
Strange issue
Please advice what could be the issue ?
Below is my code
public class GetImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public GetImage()
{
}
public void ProcessRequest(HttpContext context)
{
if (context != null)
{
if (!string.IsNullOrEmpty(context.Request.Params["side"]))
{
bool isFront = false;
if (context.Request.Params["side"].Equals("Front"))
{
isFront = true;
}
else
{
isFront = false;
}
ICache Cache = CacheManager.SessionCache;
DepositState depState = (DepositState)Cache[Constants.DepositSession];
if (depState != null)
{
byte[] imageByteArray = null;
System.IO.MemoryStream imageMemoryStream = null;
try
{
if (isFront)
{
imageByteArray = System.Convert.FromBase64String(depState.FrontJpegBase64);
}
else
{
imageByteArray = System.Convert.FromBase64String(depState.BackJpegBase64);
}
imageMemoryStream = new System.IO.MemoryStream(imageByteArray);
using (System.Drawing.Image img = System.Drawing.Image.FromStream(imageMemoryStream))
{
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch(Exception ex)
{
Log.Error(Constants.DefaultErrorCode, "Exception occured while converting image to Base 64 in GetImage.ashx.cs" + ex);
}
imageMemoryStream.Close();
context.Response.Flush();
}
else
{
Log.Error(Constants.DefaultErrorCode, " Deposit State object is nullin GetImage.ashx ");
}
}
}
else
{
Log.Error(Constants.DefaultErrorCode, "Context is null in the Process Request ");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
I don't see where you are setting the context.Response.ContentType. I haven't tested this, but I wonder if the missing header would cause unpredictable browser behavior.

Resources