I have a fileupload control and a button in a webform.When i click on the button after selecting fileupload,it should save the image and rename it with a GUID.
protected void btnUpload_Click(object sender, EventArgs e)
{
string fileName = string.Empty;
string filePath = string.Empty;
string extension = string.Empty;
try
{
//Check if Fileupload control has file in it
if (FileUpload1.HasFile)
{
// Get selected image extension
extension = Path.GetExtension(FileUpload1.FileName).ToLower();
//Check image is of valid type or not
if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
{
//Cretae unique name for the file
fileName = Guid.NewGuid().ToString() + extension;
//Create path for the image to store
HiddenField1.Value = fileName;
filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
//Save image in folder
FileUpload1.SaveAs(filePath);
//Show the panel and load the uploaded image in image control.
//pnlCrop.Visible = true;
}
The above code works just fine,saves the image and passes the GUID to the hiddenfield.Now i want to pass the value of hiddenfield to a client side variable and then display it as an alert.
<script type="text/javascript">
function showfilename() {
setTimeout(function () {
var dpGUID = document.getElementById('<%= HiddenField1.ClientID %>').value;
alert(dpGUID);
},3000)
}
</script>
Reason for using timeout? Because i want to read value of hiddenfield after it has been assigned the value on button click.
Note:I am using two functions on Buttonclick.One on client side and other on server side as follows :
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Button" OnClientClick="showfilename()" />
Is it possible? If yes,what could be causing a problem?
Try using a RegisterClientScriptBlock
protected void btnUpload_Click(object sender, EventArgs e)
{
/*All your code here*/
//instead of HiddenField1.Value = fileName; write the line below
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "callJsFunction", "alert('" + fileName + "');", true);
}
and now you can get rid of the OnClientClick="showfilename() and the HiddenField
Related
I have a requirement to read image data from SQL Server (company logo) and keep it in localStorage. This company logo is displayed in the master page left sidebar so that in every client page it will be visible.
I use 3 JS functions in the Master page for this purpose.
function storageCheck() {
if (localStorage.getItem("imgData") === null) //check availability
document.getElementById('<%=hdfStorage.ClientID %>').value = "true"; //assign true to a hidden field
else
document.getElementById('<%=hdfStorage.ClientID %>').value = "false";
}
function storelogo(imgData) { //store image data
localStorage.setItem("imgData", imgData);
}
function getImg() { //get data
var dataImage = localStorage.getItem('imgData');
document.getElementById('imgCompanyLogo').src = dataImage;
alert('got')
}
In the code behind of the Master page I am calling these JS functions
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (!IsPostBack)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "checkfn", "storageCheck()", true);
if (hdfStorage.Value == "true")
ScriptManager.RegisterStartupScript(this, this.GetType(), "storelogoo", "storelogo('" + <Base64String img data from database> + "');", true);
else if (hdfStorage.Value == "false")
ScriptManager.RegisterStartupScript(this, this.GetType(), "getlogo", "getImg();", true);
}
}
I have tried putting it in the Page_Load event but no use. The issue I am facing is these functions are not getting called and if called from the Page Load event the hiddenfield control wont get the value when I check using hdfStorage.Value == "true"
I suggest to put it in memory as singleton or session, all people work like this
I'm facing an issue where my Iframe response URL is replacing my parent(browser) URL instead of the opening inside the Iframe.
I have my Application page(default.aspx) page which I access from a browser. In that page, I loaded the iframe by passing 3 URL
./Response?Stauts=cancel
./Response?Status=Decline
./Response?Status=confirmed
Code snip of form posting to iFrame URL.
<%# Page Language="C#" %>
<script runat="server">
bool _postLoadCustom = false;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
string CANCELURL = Request.Params["CANCELURL"];
string ERRORURL = Request.Params["ERRORURL"];
string REDIRECTURL = Request.Params["REDIRECTURL"];
{
NameValueCollection data = new NameValueCollection();
data.Add("__CANCELURL", CANCELURL);
data.Add("__ERRORURL", ERRORURL);
data.Add("__REDIRECTURL", REDIRECTURL);
RedirectAndPOST(this.Page,"https://IframeURL/Content", data);
}
}
#region RedirectAndPost
public static void RedirectAndPOST(Page page, string destinationUrl,NameValueCollection data)
{
string strForm = PreparePOSTForm(destinationUrl, data);
page.Controls.Add(new LiteralControl(strForm));
}
private static String PreparePOSTForm(string url, NameValueCollection data)
{
string formID = "PostForm";
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"" + formID + "\" name=\"" +
formID + "\" action=\"" + url +
"\" method=\"POST\">");
foreach (string key in data)
{
strForm.Append("<input type=\"hidden\" name=\"" + key +
"\" value=\"" + data[key] + "\">");
}
strForm.Append("</form>");
//Build the JavaScript which will do the Posting operation.
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var v" + formID + " = document." +
formID + ";");
strScript.Append("v" + formID + ".submit();");
strScript.Append("<" + "/script>");
return strForm.ToString() + strScript.ToString();
}
#endregion
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
Loading...
</body>
</html>
As I complete the Iframe journey and click Submit(iframe button), I get the one of the URL which I passing to 3rd party service via Iframe. From this URL I extract the information(status). the URL I received in response should be redirected to Iframe but it is replacing my current URL(default.aspx).
Below code is my response page which i used to extract information from response URL and store into the session.
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
public void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
return;
}
else
{
string url = HttpContext.Current.Request.Url.AbsolutePath;
string status = Request.QueryString["status"].Split('-')[0];
string sessionID = Request.QueryString["status"].Split('-')[1];
string exampleServerUrl = ConfigurationManager.AppSettings["ServerURL"];
String sessionName = "ProductBase_1_0_0_0";
string request =
#"
<server><requests>
<resumeSession sessionID=""{0}""/>
<Session.setElementRq path=""data/policyAdmin/policynotes/FITSStatus"" value=""{1}""/>
</requests></server>";
request = string.Format(request, sessionID, status);
string response = this.HTTPPost(exampleServerUrl, request);
}
}
private string HTTPPost(string url, string requestXML)
{
string result = null;
System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
wr.Timeout = 90000;
wr.ServicePoint.ConnectionLimit = 10;
wr.Method = "POST";
wr.ContentType = "text/xml";
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(requestXML);
System.IO.Stream strm = wr.GetRequestStream();
strm.Write(byteArray, 0, byteArray.Length);
strm.Close();
System.Net.WebResponse resp = wr.GetResponse();
System.Text.Encoding enc = Encoding.GetEncoding("utf-8");
System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream(), enc);
result = reader.ReadToEnd();
reader.Close();
resp.Close();
return result;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="paypageresponce" runat="server" method="post">
<!--#include file="Response.html"-->
<label>Payment in progress...</label>
</form>
</body>
</html>
I include the Response.html page from which I have called the javascript function to click my Application button automatically.
I have intensively googled to get the solution but no luck. I tried to replace the iFrame URL but it was not allowed due to security by service.
I have debugged the code and reach to point as when I clicked the submit button of iframe, my response.aspx url replace my default.aspx.
Any one can let me know why response URL is replacing insted of redirected to IFrame.
I want to hide file upload control behind label I found solution for that on this link:
Styling an input type="file" button
There was a link to this example: http://jsfiddle.net/4cwpLvae/
Now by clicking on label it open file uploader and after uploading file it hides file upload tab, but I want to save file uploaded by that uploader in database throuh a function in aspx.cs file. How may I call that function?
This link did't help for me
How to call code behind function from label.text in asp.net
using file uploader in label is just for styling.
Here is my function that I want to call
protected void Button1_Click(object sender, EventArgs e)
{
if (!inputfile.HasFile)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);
//Response.Write("No file Selected"); return;
}
else
{
string filename = Path.GetFileName(inputfile.PostedFile.FileName);
string extension = Path.GetExtension(filename);
string contentType = inputfile.PostedFile.ContentType;
HttpPostedFile file = inputfile.PostedFile;
byte[] document = new byte[file.ContentLength];
file.InputStream.Read(document, 0, file.ContentLength);
/* Stream fs = inputfile.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);*/
if ((extension == ".pdf") || (extension == ".doc") || (extension == ".docx") || (extension == ".xls")
|| (extension == ".pptx"))//extension
{
if (file.ContentLength <= 31457280)//size
{
FYPEntities2 obj = new FYPEntities2();
tblFile us = new tblFile();
us.Name = filename;
us.ContentType = contentType;
us.Data = document;
// us.Data = bytes;
us.Date = DateTime.Now;
obj.tblFiles.Add(us);
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('Hello World');", true);
obj.SaveChanges();
Response.Redirect(Request.Url.AbsoluteUri);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "filesize();", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "invalidformat();", true);
}
}
}
I think you are looking for this. Put a LinkButton on the page and give it no Text, so it is not visible for the user but does still exists.
<style>
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
</style>
<label for="<%=FileUpload1.ClientID %>" class="custom-file-upload">
<i class="fa fa-cloud-upload">Custom Upload</i>
</label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="Button1_Click"></asp:LinkButton>
Then in code behind attach an onchange attribute to FileUpload1 with the UniqueID of LinkButton1. When the upload changes, javascript will file the PostBack event of the LinkButton thus automatically uploading the file.
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes.Add("onchange", "__doPostBack('" + LinkButton1.UniqueID + "','')");
}
I am using "File Upload" control and C# coding (backend) for uploading files(.jpeg/.png/.pdf) in my web application.
The files uploaded through this control should be saved in the server.
Everything is working fine but the problem i am facing is when a file type of xlsx or doc is been saved and the extension of that file is changed to .png or .jpeg and is being uploaded it is being uploaded into the server without any error.
While I am trying to open that image or pdf file in server it is as usually showing the error message the file cant be opened.
I have done extension validation but it does not show any effect here in this case.
Can anyone help me to get rid of this problem.(Either C# coding or Jquery Or javascript will do)
Here is how finally able to get the validation as I need using "Header codes":
System.IO.BinaryReader r = new System.IO.BinaryReader(FileUpload1.PostedFile.InputStream);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
}
r.Close();
if (fileclass != "3780" || fileclass != "255216" || fileclass != "13780") /*Header codes (3780-PDF);(255216-JPG,JPEG);(13780-PNG)*/
{
/*Your code goes here(things to do with the file uploaded)*/
}
For getting values for other file formats try uploading the file and set break point and get the header code.
Can you show us how your validation looks like ?!
There is two way to check the extension of a file that you are uploading. It should be like this following :
//In your aspx file :
<asp:FileUpload ID="FileUploadControl" runat="server"/>
<asp:Button runat="server" id="Btn_Upload" text="Upload" onclick="Btn_Upload_Click" />
//In your aspx.cs file :
// First soluce
protected void Btn_Upload_Click(object sender, EventArgs e)
{
if (FileUploadControl.PostedFile.ContentType != "application/pdf")
{
//Not an PDF
}
}
// Second soluce :
protected void Btn_Upload_Click(object sender, EventArgs e)
{
string extension = Path.GetExtension(FileUploadControl.PostedFile.FileName);
if (extension != ".pdf")
{
//Not an PDF
}
}
Of course, on these code sample you can add for exception for JPEG / PNG / ...
Edit, Updated
But my problem is the extension is a proper one which i need to upload
but the file type is not i mean an excel sheet can be saved with
extension jpeg
You can use FileReader, .readAsBinaryString() to check for file headers; e.g, JFIF for .jpeg, .jpg; PNG for .png; PDF for .pdf; RegExp.prototype.test() with RegExp /JFIF|PNG|PDF/
Use accept attribute at <input type="file"> element with value set to ".jpeg,.jpg, .png,.pdf" to exclude files with extensions other than .jpeg, .jpg, .png or .pdf from being able to be selected by user at Choose File dialog.
document.querySelector("input[type=file]")
.addEventListener("change", function(e) {
console.log(e.target.files[0].type);
var reader = new FileReader();
reader.onload = function(event) {
console.log(event.target.result
, /JFIF|PNG|PDF/.test(event.target.result))
}
reader.readAsBinaryString(e.target.files[0])
})
<input type="file" accept=".jpeg,.jpg,.png,.pdf" />
There are many image format, like webp for example why not support them all?
You can convert them client side before you upload them using canvas...
function convertImage(image, mimetype, quality) {
return new Promise(function(resolve){
var canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
canvas.getContext("2d").drawImage(image, 0, 0)
canvas.toBlob(resolve, mimetype, quality)
})
}
if(input.files[0].type === 'application/pdf') {
// upload directly (not a image)
} else {
var img = new Image
img.onerror = function() { /* not an image */}
img.onload = function() {
convertImage(img, 'image/png', 1).then(function(blob){
// upload the converted image
fetch('upload', {method: 'POST', body: blob})
})
}
img.src = URL.createObjectURL(input.files[0])
}
then you use this to help filter out the accepted files you want
<input type="file" accept="application/pdf, image/*">
I have a scenario where I want to check if user adds data with same date and same region again, it should give him a prompt alert.
I tried this with code behind,like below:-
protected void btnSave_Click(object sender, EventArgs e)
{
DataTable dtExcel = new DataTable();
dtExcel.Clear();
string StrCount = String.Empty;
string connString = "";
HttpPostedFile File = FileUpload1.PostedFile;
string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
string path = FileUpload1.PostedFile.FileName;
string Filename = path.Substring(path.LastIndexOf("\\") + 1, path.Length - path.LastIndexOf("\\") - 1);
path = Server.MapPath(#"~/Excels/" + "/" + Filename.ToString());
File.SaveAs(path);
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT * FROM [Sheet 1$]";
OleDbConnection conn = new OleDbConnection(connString);
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter daExcel = new OleDbDataAdapter(cmd);
daExcel.Fill(dtExcel);
conn.Close();
DataTable DtMain = CF.ExecuteDT("select Tran_type, Order_Date, Region_Mkey from WMS_Future_Del_Order_Hdr where Tran_type = '" + CmbTypeOfAsn.SelectedValue + "' and Order_Date = convert(datetime,'" + TxtEdate.Value + "',103) and Region_Mkey = '" + ddlRegion.SelectedValue + "'"); // checks the duplicate records here
if (DtMain.Rows.Count > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "myTestFunction()", true);
}
Also see my function for prompting the alert for duplicate message
function myTestFunction() {
if (confirm('Are you sure you want to override the file ?')) {
return true;
}
else {
return false;
}
}
but what happens here is even after cancel click, the excel file is uploaded and gets saved. I dont know why
Although Abbas Kapasi's solution based on AJAX is good one (and you do not want to/can not use the solution based on CheckBox as I suggested in my other post codebhind-javascript-alert-for-yes-and-no-not-working-exactly), if you are not familiar with AJAX or don't want to use AJAX then you may achieve it using following approach. It may seem a bit odd but you may modify it according to your requirements:
I am splitting the code to upload and find existing file/record in one procedure and the code to write/overwrite the records in another sub-procedure.
Then I am using two LinkButtons, LinkButtonLoad and LinkButtonOverwrite.
LinkButtonLoad will be attached to the call the main procedure which uploads and finds existing file/record. LinkButtonOverwrite will call the procedure to write/overwrite the records. LinkButtonOverwrite will remain hidden from the user.
In the first procedure if the system finds existing file/record it will show a client side prompt to the user to overwrite or not. If the file/record does not exist it will call second sub-procedure to write the records.
On client side, if the prompt is displayed for existing file/record and the user selects Cancel/No the process will not proceed. If the user selects OK/Yes then I'll be calling the procedure linked to the LinkButton2 to overwrite the records.
Now putting it all together:
In aspx/front end
<asp:LinkButton ID="LinkButtonLoad" runat="server" Text="Load Records" CssClass="button" ... />
<asp:LinkButton ID="LinkButtonOverwrite" runat="server" Text="ow" CssClass="button hidden" ... />
I'm using hidden CSS class to hide the button .hidden {display: none;}. Do NOT use visible="false" attribute, it'll not be available on the client side.
JavaScript on client side:
function myTestFunction() {
if (confirm('Are you sure you want to override the file ?')) {
// get the action attribute of the hidden LinkButtonOverwrite here and call it on OK
// as an alternative you may also invoke the click event of this button
var defaultAction = $('#<%=LinkButtonOverwrite.ClientID %>').prop("href");
window.location.href = defaultAction;
}
else {
return false;
}
}
LinkButtonLoad in code behind:
protected void LinkButtonLoad_Click(object sender, EventArgs e)
{
//==============================================================
// YOUR CODE TO UPLOAD THE FILE, SAVE IT SO WE MAY USE IT AGAIN
//==============================================================
if (DtMain.Rows.Count > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "myTestFunction()", true);
}
else
{
MySubToOverwrite();
}
}
LinkButtonOverwrite in code behind:
protected void LinkButtonOverwrite_Click(object sender, EventArgs e)
{
//===========================================================
// AS THE FILE IS ALREADY UPLOADED IN LINKBUTTONUPLOAD_CLICK
// YOU MAY ACCESS IT AND PERFORM REQUIRED OPERATIONS
//===========================================================
MySubToOverwrite();
}
MySubToOverwrite() code in behind:
private void MySubToOverwrite()
{
//==========================================================
// OVERWRITE YOUR RECORDS HERE
// FROM THE FILE ALREADY UPLOADED IN LINKBUTTONUPLOAD_CLICK
//==========================================================
}
Detecting duplicate records
There are a few ways you can do this. Just going to touch on the big picture here, in order of my personal preference:
Easiest method: Don't check. Prompt first. Provide a checkbox up front.
Use 2 Ajax requests: one to check for existing record, and another to save the file (if user said "OK" or if file not yet exists). Challenge: multiuser environments.
Multi-step POST back. Server code injects a dynamic control (or shows a hidden static one) that prompts user to overwrite. Ugly, but does not require JS. You may remember this from the '90s.
Versioning: more advanced, more complex, but for Enterprise systems this is the way to go. Do not overwrite files with same identifier; store a different version of it. Then you get a nice history and audit trail of who changed it. Makes it easy to go back to fix mistakes, blame people, etc.
Canceling the PostBack (if using option 3 or other postback method)
You need to bind to the correct button, and to prevent POST to the server (AKA "postback") you must return false in either
the click event handler of the rendered input type="button"
or
the submit event handler if the form
You can accomplish this by embedding the return value to myTestFunction() in the asp:Button itself:
<asp:Button ID="btnSave" runat="server" Text="Save"
OnClientClick="if(!myTestFunction()){return false;}"
OnClick="btnSave_Click" />
<script>
function myTestFunction() {
return confirm('Override the file?');
}
</script>
use ajax function with webservice to check the same data and region
Submit button code
<asp:Button ID="btnupload" runat="server" OnClientClick="javascript return checkData()"
Text="Upload" OnClick="btnupload_Click"></asp:Button>
Javacript
<script>
function checkData() {
$.ajax({
type: "POST",
url: "demo.aspx/functionName1",
data: "{parameter1:'" + param1 "',parameter2:'" + param2 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.d == 'Yes'){
if (confirm('Are you sure you want to override the file ?')) {
return true;
}
else {
return false;
}
}
else{
return true;
}
}
});
}
</script>
C# Code
using System.Web.Services; --- use this class
[WebMethod]
public static string functionName1(string parameter1, string parameter2)
{
------------------------------;
if(check Condition)
return "Yes";
else
return "No"
}
In reality, you just need the following to make it work. Use RegisterOnSubmitStatement instead of RegisterStartupScript. It would let you add script that executes in response to the button's onclick event. The script is executed before the button event is invoked, and gives you an opportunity to cancel the event.
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// You can place this in any method where you want to do the validation.
String scriptText =
"return confirm('Are you sure you want to override the file ?')";
ClientScript.RegisterOnSubmitStatement(this.GetType(),
"ConfirmSubmit", scriptText);
}
protected void btnSave_Click(object sender, EventArgs e)
{
}
Markup :
<asp:Button id="ConfirmSubmit" runat="server" OnClick="btnSave_Click"/>