I'm saving a file with the asyncfileupload ajax plugin from the ajax toolkit and when I save it I'm changing the filename (to avoid multiple files with the same name).
After the file is uploaded, the user needs to know what the file has been named so I'm using this javascript code on the onclientuploadcomplete event.
function UploadComplete(sender, args) {
alert(args.get_fileName());
}
This works except it gets the old name, not the new name (which is determined server-side). Is there any way to get it to return the new name rather than the old name? Or any work around to achieve this?
This is my code in the code behind the get the new filename:
string filename = DateTime.Now.ToString("dMyHmsf") + e.filename;
string strPath = MapPath("~/SavedImages/") + filename;
AsyncFileUpload1.SaveAs(strPath);
I got the answer from http://forums.asp.net/post/4139037.aspx It works for me...
copied code from there:
<asp:ToolkitScriptManager runat="server">
</asp:ToolkitScriptManager>
<!--This script snippet must be located below the ScriptManager-->
<script type="text/javascript">
Sys.Extended.UI.AsyncFileUpload.prototype.newFileName = null; //I did not use this line
function uploadcomplete(sender, e) {
alert(sender.newFileName);
}
</script>
<asp:AsyncFileUpload ID="AsyncFileUpload1" OnClientUploadComplete="uploadcomplete"
runat="server" OnUploadedComplete="AsyncFileUpload1_UploadedComplete1" />
the code behind:
protected void AsyncFileUpload1_UploadedComplete1(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this,
this.GetType(), "newfile",
"window.parent.$find('" + AsyncFileUpload1.ClientID + "').newFileName='newfile.jpg';", true);
}
How about writing the filename to a hiddenfield in the codebehind and the reading that value in your clientside code?
Related
I am creating a directory of files for an internal website. The user will access the page and insert the location and filename and submit the information to a database. I tried using file upload to open Windows Explorer so the user can locate the file and path. However, asp file upload will not allow me to capture the path on the client side. Since this is an internal website, does Internet Explorer or Windows Registry have a permissions setting for trusted scripts similar to trusted sites?
I created a JQuery Script to copy the the path to a textbox but I get a error message saying "C:\fakepath\test.pdf". test.pdf is the filename but c:\fakepath is not the path. I have tried multiple server variables but those just tell the paths on the server end.
<script>
$(document).ready(function(){
$("#button").click(function(){
$("#text1").val($("#text").val());
});
});
</script>
<input type="file" id="text" />
<input type="text" id="text1" />
<input type="button" value="Click Me!" id="button" />
To access the local path you need to use ActiveX object in your web page. It can help you to get the path in IE.
For working with Files and directory you should make a server object as Scripting.FileSystemObject then with GetDirectory() method can get a directory object.
Sample code:
var Fo =new ActiveXObject("Scripting.FileSystemObject");
var StrOut = new String();
var FileName = new String();
var Extention = new String();
function FindFile(FOo)
{
var FSo = new Enumerator(FOo.Files);
for(i=0;!FSo.atEnd();FSo.moveNext())
{
if(FileName == "*" || FSo.item().name.slice(0,FSo.item().name.lastIndexOf(".")).toLowerCase().indexOf(FileName)>-1)
if(Extention == "*" || FSo.item().name.slice(FSo.item().name.lastIndexOf(".")+1).toLowerCase().indexOf(Extention)>-1){
StrOut += "<tr "+ ((i%2)? "":"bgcolor=#DDAA55") +"><td width=50%><font class=find>" + FSo.item().path + "</font></td><td width=25%><font class=find>" + FSo.item().type + "</font></td><td width=50%><font class=find>"+ String(FSo.item().size/(1024*1024)).slice(0,3) +" MB</font></td></tr>";
i++
}
}
}
function Scan()
{
FileName = (search.value.lastIndexOf(".")>-1)? search.value.slice(0,search.value.lastIndexOf(".")):(search.value.length>0)? search.value.toLowerCase():"*"; //Get Searched File Name
Extention = (search.value.lastIndexOf(".")>-1)? search.value.slice(search.value.lastIndexOf(".")+1).toLowerCase():"*"; // Get Searched File Extention Name
if(path.value.length>0 && Fo.FolderExists(path.value)){
StrOut = "<table border=0 width=100% cellspacing=0>"
FindFile(Fo.GetFolder(path.value));
outPut.innerHTML = StrOut+"</table>";
}
else alert("Insert Correct Path Address");
}
For detailed information and example code, You can refer link below and download the sample file.
Find files with JavaScript
In my existing application file name contains Single quote (') Special character EXample file name: Zahed's.doc. When I am trying to download this file I am not able to download because the file name is contained 's .
Below is my uploading design code:
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="textfield_new1" />
My uploading .cs Code:
bo.Para21 = FileUpload1.FileName.ToString();//ResumePath
string FinalFileName = Convert.ToString(Sno) + bo.Para21;
FileUpload1.PostedFile.SaveAs(Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Resumes/" + FinalFileName);
Below is my Downloading file design code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkbtn_ResumeUpload" runat="server" CssClass="cv_heading" OnClick="lnkbtn_ResumeUpload_Click"></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
Button click for Dowloading code:
protected void lnkbtn_ResumeUpload_Click(object sender, EventArgs e)
{
string path = lnkbtn_ResumeUpload.Text;
string ResumePath = System.Configuration.ConfigurationManager.AppSettings["ResumePath"].ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "SCRIPT", "window.open('"+ResumePath+path + "')", true);
}
My issue is already 800 users are uploaded with the file name 's and I am not able to download that application, how to resolve this type of issue.
Try to encode the filename using HttpUtility.UrlEncode()
https://msdn.microsoft.com/en-us/library/4fkewx0t.aspx
Example:
If your filepath is called "path" you need to encode it first, then send it to javascript.
string filePath = HttpUtility.UrlEncode(path);
System.Web.UI.ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "SCRIPT", "window.open('"+ filePath + "')", true);
Another solution is HttpUtility.JavaScriptStringEncode which encode your javascript string completely that contains apostrophe.
The problem is that the generated javascript will be broken because it will be:
window.open('...Zahed's.doc');
So the '-character will break your script. Easiest solution is to replace ' with " in your code on the window-open part:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "SCRIPT", "window.open(\"" +ResumePath + path + "\")", true);
I have image on aspx page as:
<asp:Image ID="imgOrgLogo" runat="server" Width="50px" Height="35px" AlternateText="Image Not Found" />
I have ready path for it in database, and I am fetching image name from database and setting up its path as:
string path = obj.ExecuteScalar(sql);
imgOrgLogo.ImageUrl = "/OrgImages/" + path;
imgOrgLogo.DataBind();
from string path I get the image name.
I checked folder OrgImages contains specified image.
But image is not viewing after running this code.
When i done inspect element from browser its showing:
<img id="MainContent_imgOrgLogo" src="" alt="Image Not Found"
style="height:35px;width:50px;">
Path is not getting settled.
What is wrong in my code??
Please help me.
Try:
<img id="MainContent_imgOrgLogo" src="" alt="Image Not Found" style="height:35px;width:50px;" runat="server" />
I added runat="server" so you can access the <img ID in codebehind and set the src.
Example: MainContent_imgOrgLogo.Src = (YOUR IMAGEPATH)
Or try (since you are talking about a ddlOrganization_SelectedIndexChanged):
if(!IsPostBack)
{
string path = obj.ExecuteScalar(sql);
imgOrgLogo.ImageUrl = "/OrgImages/" + path;
imgOrgLogo.DataBind();
}
Edit:
but on selection it should change the image.
If you want to achieve that, you should put the <img-attribute inside a UpdatePanel and on the ddlOrganization_SelectedIndexChanged-event you should paste your .ImageURL-code.
Change the line
imgOrgLogo.ImageUrl = "/OrgImages/" + path;
with
imgOrgLogo.ImageUrl = "~/OrgImages/" + path;
and remove
imgOrgLogo.DataBind();
I have a asp FileUpload control in my aspx page.
And the code behind to check file's extension and then insert them into database:
private string Write(HttpPostedFile file, string table)
{
string fileNameMain = Path.GetFileName(file.FileName);
// check for the valid file extension
string fileExtension = Path.GetExtension(fileNameMain).ToLower();
if (fileExtension.Equals(".pdf") || fileExtension.Equals(".doc"))
{
...insert fileupload into database
}
else
{
LabelError.Text = "Extension of files are not allowed.";
return null;
}
}
With the code above, it checks the extension and then show the message "Extension of files are not allowed." in a LabelError if the fileupload is not allowed.
Now, I'm required to do the "check-extension" in the other way: at the moment the client click and choose FileUpload, an alert show "Extension of files are not allowed.".
I need a way to make an alert show at the momment the FileUpload choosed in browser. Help!!!!
Hi but if you want an Alert (JavaScript) but first you need an postback action to execute code vb and the alert for example you could use a button to execute this method. You can show alert with this code
string script = "alert('Extension of files are not allowed');";
ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", script , true);
I'm using twitter bootstrap. I'm changing the profile picture. I'm just saving the picture in a folder and retrieving it again. It works fine in local system but it is not working after deploying the code in the server. But picture is getting saved in the folder and not getting Changed in .aspx page. When i log out and log in again,its getting refreshed.
Here is my code :
<img runat="server" id="ImgPic" />
<input type="file" id="fileUpload" runat="server"/>
Change
<asp:Button ID="btnChangeUserPic" runat="server" OnClick="btnChangeUserPic_Click"
class="hidden" />
function ChangePicture(){
$('#btnChangeUserPic').click();
}
protected void btnChangeUserPic_Click(object sender, EventArgs e)
{
try
{
string filePath = Server.MapPath("~/Upload/Images/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string file = fileUpload.PostedFile.FileName.ToLower();
HttpPostedFile hpfFile = fileUpload.PostedFile;
if (file != "")
{
string fileExtn = Path.GetExtension(hpfFile.FileName).ToLower();
if (fileExtn == ".jpg")
{
string filename = filePath +System.IO.Path.GetFileName(hpfFile.FileName);
if (File.Exists(filename))
{
File.Delete(filename);
}
hpfFile.SaveAs(filename);
ImgPic.src= filename;
}
}
}
catch (Exception ex)
{
}
}
The Picture should get updated in master page also.
Thank you all in advance for your response.
I'm not 100% sure what you mean by 'getting refreshed' but.. the filepath on your server is not going to be the same as on you local machine. Use Server.MapPath instead of a simple string;
http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
Also check you permissions to the folder and show us the code in whatever UI page that actually displays the picture, how is that getting set?
My guess (there's not enough info) is that ImgPic.src is holding the URL for the img tag. This would explain why it works locally but not on the server, because you've set
ImgPic.src= filename;
it should be set to the URL, not the mapped path.
If it's not that please post info on where the img is getting it's src set.