Missing Loading Image From Database Use Handler.ashx - asp.net

I use the Handler.ashx to get and display images from database.
But they didn't all display, only 100% after request few times.
I don't know how to solve.
Handler.ashx code:
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["ImageID"] != null)
{
Byte[] bytes;
string _strModelCode = context.Request.QueryString["ImageID"];
try
{
bytes = ModelBLL.GetImage(_strModelCode);
}
catch
{
bytes = null;
}
context.Response.ContentType = "Image/jpg";
if (bytes != null)
{
try
{
context.Response.BinaryWrite(bytes);
}
catch { }
}
context.Response.End();
return;
}
}
Image Loading Code:
foreach (GridViewRow _row in gridDispaly.Rows)
{
Image img = (Image)_row.FindControl("imgModel");
img.ImageUrl = "../Handler.ashx?ImageID=" + _row.Cells[0].Text;
}
Thank you!
Error Loading Image From Database

Related

why zxing can not decode this qrcode image?

JavaSE: Exception is "com.google.zxing.NotFoundException"
Can any one help me?
The version is 3.4.1
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.1</version>
</dependency>
and the java code is there.
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Map<DecodeHintType,Object> hints = new LinkedHashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
The Exception info is :
com.google.zxing.NotFoundException
There is not anything other displayed...
But the following code can not be decoded out,It's really weird
Almost identical QR codes, one can be decoded but the other cannot be coded`
Use GenericMultipleBarcodeReader to read the QR code.
public void decodefile(String filename) {
// Read an image to BufferedImage
BufferedImage image = null;
try {
image = ImageIO.read(new File(filename));
} catch (IOException e) {
System.out.println(e);
return;
}
// ZXing
BinaryBitmap bitmap = null;
int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
RGBLuminanceSource source = new RGBLuminanceSource(image.getWidth(), image.getHeight(), pixels);
bitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
GenericMultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
try {
Result[] zxingResults = multiReader.decodeMultiple(bitmap);
System.out.println("ZXing result count: " + zxingResults.length);
if (zxingResults != null) {
for (Result zxingResult : zxingResults) {
System.out.println("Format: " + zxingResult.getBarcodeFormat());
System.out.println("Text: " + zxingResult.getText());
System.out.println();
}
}
} catch (NotFoundException e) {
e.printStackTrace();
}
pixels = null;
bitmap = null;
if (image != null) {
image.flush();
image = null;
}
}
Here is my results:
ZXing result count: 1
Format: QR_CODE
Text: https://mp-daily.bookln.cn/q?c=1201M9XUEDE

File Upload is not working in asp.net

I'm trying to upload a file using FileUpload, and it doesn't work. After I click the button, it reloads the page, but the image is not saved
Below code is from microsoft, but still not working
protected void uploadBtn_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
String path = Server.MapPath("~/Sources/images/");
if (imageUpload.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(imageUpload.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
imageUpload.PostedFile.SaveAs(path
+ imageUpload.FileName);
statusUploadLbl.Text = "File uploaded!";
}
catch (Exception ex)
{
statusUploadLbl.Text = "File could not be uploaded.";
}
}
else
{
statusUploadLbl.Text = "Cannot accept files of this type.";
}
}
Please help, thanks

How to get image from Image control and save into local directory as jpeg image in asp.net?

i am loading image from asp.net handler as below> handler fetches image using web service. Handler returns as bytes[] data.
<asp:Image ID="image1" ImageUrl="~/Handler1.ashx?id=1" runat="server"></asp:Image>
Now, I have image in the web page. I have save Image button in the web page. When button clicked, I want to save this image into local directory (c:\images) as a jpeg image. How to achieve this?
Try to use the following code for handler, which returns image data:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
bool isSave = !String.IsNullOrEmpty(context.Request["save"]);
int imgId;
if (String.IsNullOrEmpty(context.Request["id"]) || Int32.TryParse(context.Request["id"], out imgId))
throw new ArgumentException("No parameter specified");
byte[] imageData = LoadImageFromWebService(imgId); //load image from web service
context.Response.ContentType = "image/jpeg";
context.Response.AddHeader("Content-Length", imageData.Length.ToString());
context.Response.AddHeader("Content-Disposition", String.Format("{0} filename=image.jpeg", isSave ? "attachment;" : String.Empty));
context.Response.BinaryWrite(imageData);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Change asp.net page as follows:
<asp:Image ID="Image1" ImageUrl="~/Handler1.ashx?id=1" runat="server"></asp:Image>
<asp:ImageButton ID="ImageButton1" OnClick="OnImageClick" runat="server" />
In this case your OnImageClick handler in page will be:
protected void OnImageClick(object sender, ImageClickEventArgs e)
{
Response.Redirect("~/Handler1.ashx?id=1&save=1");
}
I think that you must get the path of the image control
inside the click event
as
string path = image1.ImageUrl;
and then save it to the file
hope this helps you
public class ImageHandler : IHttpHandler
{
Users objimage = new Users();
public void ProcessRequest(HttpContext context)
{
Int32 theID;
if (context.Request.QueryString["Id"] != null)
theID = Convert.ToInt32(context.Request.QueryString["Id"]);
else
throw new ArgumentException("No parameter specified");
HttpResponse r = context.Response;
r.ContentType = "image/jpeg";
context.Response.ContentType = "image/jpeg";
objimage.imageId = theID; //select image using id
Stream strm = objimage.SelectImageByID(theID);
byte[] buffer = new byte[2048];
if (strm != null)
{
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
else
{
r.WriteFile("~/img/img-profile.jpg");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

ASP.NET clear HttpContext.Current.Request.Files

How can I clear the HttpContext.Current.Request.Files list?
After the postback, this still contains the files.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
this.SaveImages();
}
private Boolean SaveImages()
{
//loop through the files uploaded
HttpFileCollection _files = HttpContext.Current.Request.Files;
//Message to the user
StringBuilder _message = new StringBuilder("Files Uploaded:<br>");
try
{
for (Int32 _iFile = 0; _iFile < _files.Count; _iFile++)
{
if (!string.IsNullOrEmpty(_files[_iFile].FileName))
{
// Check to make sure the uploaded file is a jpg or gif
HttpPostedFile _postedFile = _files[_iFile];
string _fileName = Path.GetFileName(_postedFile.FileName);
string _fileExtension = Path.GetExtension(_fileName);
//Save File to the proper directory
_postedFile.SaveAs(HttpContext.Current.Request.MapPath("files/") + _fileName);
_message.Append(_fileName + "<BR>");
}
}
lblFiles.Text = _message.ToString();
return true;
}
catch (Exception Ex)
{
lblFiles.Text = Ex.Message;
//Refill images in control????
return false;
}
finally
{
//Clear HttpContext.Current.Request.Files!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}

ASP.NET: How to persist Page State accross Pages?

I need a way to save and load the Page State in a persistent manner (Session). The Project i need this for is an Intranet Web Application which has several Configuration Pages and some of them need a Confirmation if they are about to be saved. The Confirmation Page has to be a seperate Page. The use of JavaScript is not possible due to limitations i am bound to. This is what i could come up with so far:
ConfirmationRequest:
[Serializable]
public class ConfirmationRequest
{
private Uri _url;
public Uri Url
{ get { return _url; } }
private byte[] _data;
public byte[] Data
{ get { return _data; } }
public ConfirmationRequest(Uri url, byte[] data)
{
_url = url;
_data = data;
}
}
ConfirmationResponse:
[Serializable]
public class ConfirmationResponse
{
private ConfirmationRequest _request;
public ConfirmationRequest Request
{ get { return _request; } }
private ConfirmationResult _result = ConfirmationResult.None;
public ConfirmationResult Result
{ get { return _result; } }
public ConfirmationResponse(ConfirmationRequest request, ConfirmationResult result)
{
_request = request;
_result = result;
}
}
public enum ConfirmationResult { Denied = -1, None = 0, Granted = 1 }
Confirmation.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer != null)
{
string key = "Confirmation:" + Request.UrlReferrer.PathAndQuery;
if (Session[key] != null)
{
ConfirmationRequest confirmationRequest = Session[key] as ConfirmationRequest;
if (confirmationRequest != null)
{
Session[key] = new ConfirmationResponse(confirmationRequest, ConfirmationResult.Granted);
Response.Redirect(confirmationRequest.Url.PathAndQuery, false);
}
}
}
}
PageToConfirm.aspx:
private bool _confirmationRequired = false;
protected void btnSave_Click(object sender, EventArgs e)
{
_confirmationRequired = true;
Response.Redirect("Confirmation.aspx", false);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
if (_confirmationRequired)
{
using (MemoryStream stream = new MemoryStream())
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
stream.Flush();
Session["Confirmation:" + Request.UrlReferrer.PathAndQuery] = new ConfirmationRequest(Request.UrlReferrer, stream.ToArray());
}
}
base.SavePageStateToPersistenceMedium(state);
}
I can't seem to find a way to load the Page State after being redirected from the Confirmation.aspx to the PageToConfirm.aspx, can anyone help me out on this one?
If you mean view state, try using Server.Transfer instead of Response.Redirect.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
use this code this works fine form me
public class BasePage
{
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Save the last search and if there is no new search parameter
//Load the old viewstate
try
{ //Define name of the pages for u wanted to maintain page state.
List<string> pageList = new List<string> { "Page1", "Page2"
};
bool IsPageAvailbleInList = false;
foreach (string page in pageList)
{
if (this.Title.Equals(page))
{
IsPageAvailbleInList = true;
break;
}
}
if (!IsPostBack && Session[this + "State"] != null)
{
if (IsPageAvailbleInList)
{
NameValueCollection formValues = (NameValueCollection)Session[this + "State"];
String[] keysArray = formValues.AllKeys;
if (keysArray.Length > 0)
{
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = new Control();
currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on"))
((CheckBox)currentControl).Checked = true;
}
}
}
}
}
}
if (Page.IsPostBack && IsPageAvailbleInList)
{
Session[this + "State"] = Request.Form;
}
}
catch (Exception ex)
{
LogHelper.PrintError(string.Format("Error occured while loading {0}", this), ex);
Master.ShowMessageBox(enMessageType.Error, ErrorMessage.GENERIC_MESSAGE);
}
}
}

Resources