I have an upload image function that uploads images to the server but I am only able to add images into the server until the session ends. Once the session ends , I noticed that the images uploaded are not stored into my local solution and after some research I found out that we could make uploaded files be stored into our solution even when the session ends but I am unsure of how to implement it. I am very new to this and would appreciate all help given.
For now this is the code I have that allows me to upload my image:
protected void btnConfirm_Click(object sender, EventArgs e)
{
string uploadedPhoto = "";
if (uploadImage.HasFile)
{
string savePath;
//Find the filename extension of the file to be uploaded.
string fileExt = Path.GetExtension(uploadImage.FileName);
//rename the uploaded file with name
uploadedPhoto = txtName.Text + fileExt;
savePath = MapPath("~/Images/profile pictures/" + uploadedPhoto);
try
{
uploadImage.SaveAs(savePath);
lblMsg.Text = "Image uploaded!";
imgprw.ImageUrl = "~/Images/profile pictures/" + uploadedPhoto;
}
catch (IOException)
{
lblMsg.Text = "Image upload failed!";
}
catch (Exception ex)
{
lblMsg.Text = ex.Message;
}
}
}
I see your code is right because I used same way to upload and store image into folder like you.
string path = Server.MapPath("~/Photos/" + f.FileName);
f.SaveAs(path);
May I see your full code ?
Related
I have this class in an asp web form and I am trying to allow the download from users only if they have the password and the link to the file that is sent to them.
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//Get the filename from the link and the password entered by the user
string savefilename = Request.QueryString["file"];
string password = txtPassword.Text.Trim();
//Make sure that the password maches for the requested file
if (BLCustomerFile.IsUserAuthenticated(savefilename, password))
{
//Check if the file still exists on the server
string filename = savefilename.Substring(32);
string fileserverpath = Server.MapPath("~/uploads/" + savefilename);
if (File.Exists(fileserverpath))
{
//Response back with the file -- file download
FileInfo fileInfo = new FileInfo(fileserverpath);
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
Response.AppendHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(fileInfo.FullName);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
else
{
lblMessage.Text = "File No longer exists on the server.";
}
}
else
{
lblMessage.Text = "You are not authorized to download this file.";
}
}
catch (Exception ex)
{
lblMessage.Text = "Some error occurred. Please try again later.";
}
}
The problem: The link I give to the user is url+filename+extension, when it is pasted in the browser the file get downloaded immediately. Is there a way to stop this to happen and to force the above code to execute and therefore to check the password?
I know I can change the logic of the system but if there is a solution I would leave it in this way to avoid to have to give to the customer url, file name and password separately.
I am developing a complaint form. In this this form, I must make a function that uploads a file and then delete the file that was uploaded. I can upload a file to the server, but I can't take a link of the file I upload to the server in order to delete it. Please help me. Here is my code:
public string FilePath;
protected void btAdd_Click(object sender, EventArgs e)
{
if (AttachFile.HasFile)
{
try
{
string[] sizes = {"B", "KB", "MB", "GB"};
double sizeinbytes = AttachFile.FileBytes.Length;
string filename = Path.GetFileNameWithoutExtension(AttachFile.FileName);
string fileextension = Path.GetExtension(AttachFile.FileName);
int order = 0;
while (sizeinbytes >= 1024 && order + 1 < sizes.Length)
{
order++;
sizeinbytes = sizeinbytes/1024;
}
string result = String.Format("{0:0.##} {1}", sizeinbytes, sizes[order]);
string encryptionFileName = EncrytionString(10);
FilePath = "Path" + encryptionFileName.Trim() + AttachFile.FileName.Trim();
AttachFile.SaveAs(FilePath);
}
catch (Exception ex)
{
lbMessage.Visible = true;
lbMessage.Text = ex.Message;
}
}
}
protected void btDelete_Click(object sender, EventArgs e)
{
try
{
File file = new FileInfo(FilePath);
if (file.Exists)
{
File.Delete(FilePath);
}
}
catch (FileNotFoundException fe)
{
lbMessage.Text = fe.Message;
}
catch (Exception ex)
{
lbMessage.Text = ex.Message;
}
}
Each request in asp.net creates a new object of your Page.
If you set variables during one request, they will not be available on the next request.
Your delete logic seems to depend upon FilePath being set during upload. If you want the page to remember that, keep it in the ViewState. The ViewState is maintained across requests to the same page and that would allow you to use the variable FilePath during delete.
This can be easily achieved by making FilePath a property and getting it from the ViewState.
public string FilePath
{
get
{
return (string) ViewState["FilePath"];
}
set
{
ViewState["FilePath"] = value;
}
}
YOU SHOULD DO IT IN THIS WAY.
if (imgUpload.HasFile)
{
String strFileName = imgUpload.PostedFile.FileName;
imgUpload.PostedFile.SaveAs(Server.MapPath("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
SqlCommand cmd01 = new SqlCommand("insert into img (FeaturedImg) Values (#img)", cn01);
cmd01.Parameters.AddWithValue("#img", ("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
}
With this code you can upload file in a particular location in your sites root directory.
and the path will be stored in database as string.
so you can access the file just by using the path stored in database.
If you cant understand anything. or wanna know more u can contact me or ask me here in comments.
my application take snapshots using webcam and save them in a local folder. so i'm using following code to convert my Silverlight Snapshot to a byte array and send it through the Web Service. name of my web service is ImageService.
ImageServiceSoapClient client = new ImageServiceSoapClient();
private void source_CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
{
WriteableBitmap bmp = new WriteableBitmap(320, 240);
bmp = e.Result;
byte[] buffer = bmp.ToByteArray();
client.SaveImageToLocalAsync(buffer, txtUserName.Text);
}
and this is my server side code..
[WebMethod]
public string SaveImageToLocal(byte[] buffer,string name)
{
try
{
Bitmap bmp = new Bitmap(320, 240);
using (MemoryStream stream = new MemoryStream(buffer))
{
bmp = new Bitmap(stream);
string saveString = GetFolder() + name + ".jpg";
bmp.Save(saveString, System.Drawing.Imaging.ImageFormat.Jpeg);
}
return "Servers says : Saved..!!";
}
catch (Exception ex)
{
return "Server says : " + ex.Message;
}
}
so when i run this application, i'm getting an exception saying "Server says : Parameter is not valid"..
can anyone please tell me what's wrong with this code? i spent weeks to solve this problem. please help... :( thanks...
I did browse through all the other answers but still cannot figure out what is wrong.
I am trying out a simple fileUpload in an Azure project.
It may be that I am not closing my filestream.
The following is my code:
protected void UploadButton_Click(Object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
if (FileUpload1.PostedFile.ContentType == "zip/rar/tar")
{
string fileName = FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath("~/") + fileName);
Label2.Text = "File Uploaded Successfully !";
}
else
{
Label2.Text = "File type not allowed.";
}
}
catch (Exception ex)
{
Label2.Text = "Error in File Upload. Please upload a zip/tar/rar file containing your text files.";
}
}
}
How should I close the file stream ?
Thanks
Supraja
Well, the error message says everything. The file you are trying to save as is used by "something" and therefore it's locked. Try changing the filename and it should work with no error, at least once. RD to the server if you can, and try to delete the file manually and it will tell what program is using that file. SaveAs method should not require disposal, but if there's a Close() method, call that one. Else if there is Dispose() method, call that one, after SaveAs(), and it should work well.
I've got an oob app with a webbrowser on it.
The webbrowser source is databound with a URI defined by me. The URI has a path to a webpage from my server that displays a PDF file from its hardrive.
Note that all this is done on a local network.
URI example: uri = new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
Page code-behind:
protected void Page_Load(object sender, EventArgs e)
{
string myURL = Request.Url.ToString();
string[] ParamArray = Regex.Split(myURL, "pdf=");
string Params = ParamArray[ParamArray.Length - 1];
if (Params.Length > 0)
{
Filename = Regex.Replace(Params, #"//", #"\\"); ;
if (File.Exists(Filename))
{
Response.ContentType = "Application/pdf";
Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream.
Response.End();
}
else
this.Title = "PDF Not Found";
}
}
protected void Page_Load(object sender, EventArgs e) { string myURL = Request.Url.ToString(); string[] ParamArray = Regex.Split(myURL, "pdf="); //If the URL has parameters, then get them. If not, return a blank string string Params = ParamArray[ParamArray.Length - 1]; if (Params.Length > 0) { //to the called (src) web page Filename = Regex.Replace(Params, #"//", #"\\"); ; if (File.Exists(Filename)) { Response.ContentType = "Application/pdf"; Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream. Response.End(); } else this.Title = "PDF Not Found"; } }
The first time I set the WebBrowser source everything it displays the PDF. But when I set the URI one second time the app throws an exception: Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100).
I've done a few tests and here are the results:
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://www.google.com"); ->error
1º new Uri(#"http://www.google.com");
2º new Uri(#"http://www.microsoft.com");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
3º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
I also forgot to say that when running the app from my browser (using a HTMLHost) the pages display just fine. Opening the pages using a browser will also work well.
It must be some problem with my aspx page. Any ideas?
Pedro
I've managed to resolve this by creating a new browser for each page. If you know of a more elegant solution please share.
I am not sure if I'm following the question/problem correctly but maybe loading the pages async and then assigning to webbrowser? Forgive me if I am off-base here.
public void ShowLink(string linkUrl)
{
if (App.Current.IsRunningOutOfBrowser)
{
var pageRequest = new WebClient();
pageRequest.DownloadStringCompleted += pageRequest_DownloadStringCompleted;
pageRequest.DownloadStringAsync(new Uri(linkUrl, UriKind.Absolute));
}
}
void pageRequest_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
webBrowserLink.NavigateToString(e.Result.ToString());
}