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.
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
I have a method that is helps to Create a Directory ifNotExist and Save the path of the File ,...
Now I have a little problem, There is an Exception casted when Directory.CreateDirectory(savePath); Runs. and I can't still get it right. I would like to know what I am doing wrong and how to fix it. Anyone Subjections is welcome. Thanks
Here is My Method:
protected void ASPxUpload_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
String savepath = String.Format("{0}{1}\\", MapPath(#"~\TicketUploads\"), Session["lastcallid"]);
if (!Directory.Exists(savepath))
{
Directory.CreateDirectory(savepath);
}
String savefile = String.Format("{0}{1}", savepath, e.UploadedFile.FileName);
e.UploadedFile.SaveAs(savefile);
String urlPath = String.Format("{0}{1}\\{2}", #"~\TicketUploads\", Session["lastcallid"], e.UploadedFile.FileName);
fault_detail fltdet = session.GetObjectByKey<fault_detail>(Convert.ToInt32(Session["lastcallid"]));
fltdet.hasattachment = "Y";
fltdet.AttachUrl = urlPath;
fltdet.Save();
}
}
For more details of What I trying to do:
It simple allows the web server to identify the ID of the log user. and With that ID, We should therefore create a folder in Ticketuploads Folder. Which is like we are trying to create 2 folders at the same time. That is why I use: "{0}{1}\\"
please try this
string sessionVariable = Convert.ToString(Session["lastcallid"]);
string path = Path.Combine(MapPath(#"~\TicketUploads\"), sessionVariable);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Also
I have Add Administration Permission to the Folder. As a Local user with IIS System. user Add Example: IIS_IUSRS(Username\IIS_IUSRS) That's it.
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();
Goal:
- Save a picture from my computer's harddrive to the WPF's application.
- After adding a picture, you are enable to view the picture in visual Studio after updating the solution and projects.
Problem:
I don't know HOW to save a picture inside of my WPF's application. To
be more specificed I want the picture to be saved in the map
ArticlePicture from project DataAccessLibrary.
Again, I know how to do it in ASP.net MVC but not in WPF application. The syntax from MVC doesn't work in WPF application.
Please remember that the picture is not directly from the Internet. I upload the picture directly from my personal computer to the WPF application. The WPF application is stored in my personal PC.
The input data of the picture take place in the project MediaStore
The directory address of the picture is:
"C:\Users\Fullmetalboy\Desktop\Firefox download\picture.gif"
Directory address of the project and its map ArticlePicture is:
"E:\Project\MediaStore\DataAccessLibrary\ArticlePicture\"
The goal is to add and copy the picture to the map "ArticlePicture" with this new address
"E:\Project\MediaStore\DataAccessLibrary\ArticlePicture\picture.gif
I have tried these links but unfortunately, it didn't provide me any success.
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx
http://msdn.microsoft.com/en-us/library/ms748873.aspx#_imageformats
Syntax code in WPF application
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "jpg files (*.jpg)|*.jpg|gif files (*.gif)|*.gif|jpeg files (*.jpeg)|*.jpeg";
dlg.Multiselect = false;
bool? result = dlg.ShowDialog();
if (result == true)
{
Stream fInfo = dlg.OpenFile();
using (System.Drawing.Image correctPicture = System.Drawing.Image.FromStream(fInfo))
{
if (correctPicture.Width <= 180 && correctPicture.Height <= 250)
{
var fileName = System.IO.Path.GetFileName(dlg.FileName);
var path = System.IO.Path.Combine(Server.MapPath("/Content/Images/"), fileName);
}
else
{
}
}
}
}
Syntax code in ASP.net mVC //
// POST: /Admin/Produkt_ListaCreate/
[HttpPost, Authorize(Roles = "Admin")]
public ActionResult Produkt_ListaCreate(Bok pMyBok, HttpPostedFileBase file)
{
if (file != null)
{
using (System.Drawing.Image correctPicture = System.Drawing.Image.FromStream(file.InputStream))
{
if (correctPicture.Width <= 180 && correctPicture.Height <= 250)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("/Content/Images/"), fileName);
file.SaveAs(path);
pMyBok.BokBildUrl = "/Content/Images/" + fileName;
}
else
{
TempData["message"] = "Den uppladdade bilden fungerar inte pga att den uppfyller inte storlekens och formatets kriterier.";
return RedirectToAction("index");
}
}
} // if (file != null)
_myIBookRepository.Add(pMyBok);
_myIBookRepository.Spara();
TempData["message"] = "En boken är skapad.";
return View("index");
}
Server.MapPath is not going to work in a WPF application - its for IIS applications.
Where does this WPF application run? If its running from the same machine, what directory is it being run from? You need some way for the WPF application to determine where the ArticlePicture directory resides.
Assuming you are running the WPF application from the web server, you know where the directory resides, and the WPF application has permissions to access the directory, then all you need to do is to a file copy operation. (I see no reason to save the file back out of the WPF application if it is not modified).
I suspect maybe your intention is to upload the picture to the website via the WPF application. If so you might need to explain more clearly.
Well first of all, that directory does not exist at runtime as it's compiled into an assembly. You will have to use a folder that exists on disk in which you have sufficient rights to actually right the image data.
I would say you make a folder outside the root of you webapplication in which you can write the pictures. You want this to be outside the root of your web application as you don't want to have your pictures served directly if someone knows the URL I guess.
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?