I have a FileUpload control and I am trying to upload an image to server with it but it fails. My view:
<asp:FileUpload ID="FileUploadImage" runat="server" />
And my c#:
try
{
HttpPostedFile yuklenecekDosya = FileUploadImage.PostedFile;
if (yuklenecekDosya != null)
{
FileInfo dosyaBilgisi = new FileInfo(yuklenecekDosya.FileName);
string yuklemeYeri =
Server.MapPath("~/Images/NewUrunler/" + dosyaBilgisi);
FileUploadImage.SaveAs(Path.Combine(yuklemeYeri));
}
}
//some code for catch
It does not give any error but also it doesn't upload image. I spend hours on it and only thing I get is 'yuklenecekDosya' come as null when I debug it. Why is it null ?
Related
So I'm writing a custom validator and I need to check if a file has been uploaded using the asp.net File Upload Control.
So far I have:
function validate(sender, args)
{
if ($('#<%= hdnID.ClientID%>').val() != "False")
{
args.IsValid = true;
}
else
{
if ($('#<%= fup.ClientID %>').val() != '' )
{
alert("Run some code here");
}
else
{ }
}
}
The bit that is not right is
if ($('#<%= fup.ClientID %>').val() != '' )
I'm not sure how to determine whether the control has a file or not.
Any suggestions would be awesome. Thanks.
This might not be the JQuery-est way of doing it, but I've had success with something like this:
var uploader = $get("<%= fup.ClientID%>");
if (uploader.value != "") {
//has files
}
I also usually check that uploader != null before checking the value. Hope that helps!
My guess would be that your id is not correct. The best way I can think of to handle it off the bat would be to add a cssclass to the file input element and call it through that selector
<input type="file" class="myClientFileIDWhatever" />
...
if ($('.myClientFileIDWhatever').val() != '') {
I am developing CMS for a website using MVC 5 and Entity Framework. I have an edit form for editing the events added in the database table. I am uploading the image related to Event in a server folder and storing its URL in database.
Now I want to replace the
#Html.EditorFor(model => model.Image_Url, new { htmlAttributes = new { #class = "form-control" } })
with a input with type File, so that anyone can change the image while editing the Event information. for this I have added following.
A Picture Class
public class Pictures
{
public HttpPostedFileBase File { get; set; }
}
for File Uploading in Edit Action Method of controller
if (picture.File.ContentLength > 0)
{
var fileName = Path.GetFileName(picture.File.FileName);
var path = Path.Combine(Server.MapPath("~/assets/uploads/events/"), fileName);
picture.File.SaveAs(path);
filePath = "~/assets/uploads/events/" + fileName;
}
and finaly in Edit view
<input type="file" id="File" name="File" class="form-control" />
The above logic work perfectly fine when used in Create action method, but when I use the same in edit action method the Null reference exception occur. While debugging I found that the picture.File parameter is null at line if (picture.File.ContentLength > 0).
This is working fine in Create but in Edit action method it returns null.
Any Help on this issue?
I have done it by using Request.Files. below is my code in controller Edit action method.
foreach(string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var orgDirectory = new DirectoryInfo(Server.MapPath("~/assets/uploads"));
string pathString = System.IO.Path.Combine(orgDirectory.ToString(),"events");
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if(!isExists)
{
System.IO.Directory.CreateDirectory(pathString);
}
var path = string.Format("{0}\\{1}", pathString, file.FileName); //pathString + file.FileName;
file.SaveAs(path);
}
}
This issue could occur because of general security rules for the <input type="file" /> as you can't set a value for it. So I think the only thing you can do is a create separate view for the re-creating the image for the profile, and each time user sends a picture to you treat is a new one.
I am using asp.net to create a mobile web application to manage bike parts
I have gotten the file upload working but now I need to figure out how to get an image control to display the image from its new location on a server.
I will be saving the image file path in a database I just need to figure out how to get that new file path for the image.
this is the code I am using for the file upload
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs(Server.MapPath("~/Mobile/" + FileUpload1.FileName));
}
I can likely figure this out but just in case I can't figured I would post the question now than later as it can take a while to get an answer and I have a dead line
You are going to have to use an "ImageHandler" to read the image properly.
This is how I did my handler.
public class ImageHandler : IHttpHandler
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboBlog"].ConnectionString);
public void ProcessRequest(HttpContext context)
{
try
{
string messageid = context.Request.QueryString["mid"];
conn.Open();
SqlCommand command = new SqlCommand("SELECT Image from BlogMessages WHERE Image IS NOT NULL AND MessageID=" + messageid, conn);
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
context.Response.BinaryWrite((Byte[])dr[0]);
conn.Close();
context.Response.End();
}
}
catch (Exception ex)
{
return;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
As you can tell, I use a QueryString. I use this querystring to call the image back. I call my image back in a gridview but this is how it looks...
<asp:Image ID="postImage" runat="server" ImageUrl='<%# "ImageHandler.ashx?mid="+ Eval("MessageID") %>' Width="400px" AlternateText="No Image" ImageAlign="Middle" Visible="false" />
I do set the visibility to false because it's a blog and sometimes people don't upload an image. As you can tell, the image url calls the ImageHandler where the querystring is equal to the MessageID.
This works for me, so hopefully it will help you out.
I have the following code in an asp Gridvidiew:
<asp:HyperLink ID="hlPSTNNum" CssClass="OrdRef" Text='<%# DataBinder.Eval(Container.DataItem, "PSTNNum")%>' runat="server" ToolTip='please click here to view the full record details'
NavigateUrl='<%#"https://THE URL IS HERE Searches/advancedsearchresults.asp?supplierid=" + Eval("Supplierid") + "&display1=IS%20Number&display2=Supplier&display3=Product&display4=Supplier%20Order%20Number&order1=order%20date&pstnnum=" + Eval("PSTNNum")%>' />
I think Visual Studio 2012 is playing up about the semicolons in the query string part (from "pstnnum=" + Eval("PSTNNum")%>' />" and i tried to escape them with \ (that keeps VS happy), but the browser leaves one of the slashes in at each escape.
Not sure the best practice here as im still cutting my coding teeth...
I think the more appropriate approach would be something like this:
<asp:HyperLink ID="hlPSTNNum"
CssClass="OrdRef"
Text='<%# DataBinder.Eval(Container.DataItem, "PSTNNum")%>'
runat="server"
ToolTip='please click here to view the full record details'
NavigateUrl='<%#Server.HtmlEncode("https://THE URL IS HERE Searches/advancedsearchresults.asp?supplierid=" + Eval("Supplierid") + "&display1=IS Number&display2=Supplier&display3=Product&display4=Supplier Order Number&order1=order date&pstnnum=" + Eval("PSTNNum"))%>' />
Note the use of Server.HtmlEncode and then the use of the actual values you want rather than the directly encoded values. This will make it easy to build in Visual Studio, but ensure it gets encoded when it's rendered.
EDIT
After some more research into Microsoft's code I found that the base RenderContents method for the HyperLink class is going to encode this for you. That method, internally, calls another one called ResolveClientUrl, which looks like this:
public string ResolveClientUrl(string relativeUrl)
{
if (this.DesignMode && this.Page != null && this.Page.Site != null)
{
IUrlResolutionService urlResolutionService = (IUrlResolutionService)this.Page.Site.GetService(typeof(IUrlResolutionService));
if (urlResolutionService != null)
{
return urlResolutionService.ResolveClientUrl(relativeUrl);
}
}
if (relativeUrl == null)
{
throw new ArgumentNullException("relativeUrl");
}
string virtualPathString = VirtualPath.GetVirtualPathString(this.TemplateControlVirtualDirectory);
if (string.IsNullOrEmpty(virtualPathString))
{
return relativeUrl;
}
string text = this.Context.Request.ClientBaseDir.VirtualPathString;
if (!UrlPath.IsAppRelativePath(relativeUrl))
{
if (StringUtil.EqualsIgnoreCase(text, virtualPathString))
{
return relativeUrl;
}
if (relativeUrl.Length == 0 || !UrlPath.IsRelativeUrl(relativeUrl))
{
return relativeUrl;
}
}
string to = UrlPath.Combine(virtualPathString, relativeUrl);
text = UrlPath.AppendSlashToPathIfNeeded(text);
return HttpUtility.UrlPathEncode(UrlPath.MakeRelative(text, to));
}
Since you're URL is not relative it should fall all the way to the last line, the return statement, so honestly you shouldn't have to encode it at all. This changes your code to this:
<asp:HyperLink ID="hlPSTNNum"
CssClass="OrdRef"
Text='<%# DataBinder.Eval(Container.DataItem, "PSTNNum")%>'
runat="server"
ToolTip='please click here to view the full record details'
NavigateUrl='<%#"https://THE URL IS HERE Searches/advancedsearchresults.asp?supplierid=" + Eval("Supplierid") + "&display1=IS Number&display2=Supplier&display3=Product&display4=Supplier Order Number&order1=order date&pstnnum=" + Eval("PSTNNum")%>' />
Not 100% sure if this will work, but asp.net 4.5 has <%#: which encodes automatically. you can try that and see if it works, just change the <%# to <%#:
In my webpage I'm not able to get the session variable on post back and page resfresh.
The problem is
if the page is not IsPostback then I'm able to get the session variable.
But if the page postback then the error appears.
This error comes when i upload any file to server.I am using asynchfileupload to upload a image and store it to a session variable. and later on button click i am saving data to directory.
but it is not occuring frequently.
here is my code
protected void AsynImageLoader_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (AsynImageLoader.PostedFile != null)
{
string extension = System.IO.Path.GetExtension(AsynImageLoader.PostedFile.FileName);
if (extension == ".jpg" || extension == ".gif" || extension == ".jpeg" || extension == ".png")
{
HttpPostedFile file = AsynImageLoader.PostedFile;
Session["TempImage"] = ReadFile(file);
}
}
}
on button click
var storedImage = Session["TempImage"] as byte[];
String Strthumbpath = Server.MapPath("content\\thumbnail\\");
if (storedImage != null)
{
System.Drawing.Image image = GetImage(storedImage);
if (image != null)
{
image.Save(Strthumbpath + strFileName);
}
}
///inserting values to datbase.
after somuch googling i read that when any files is adding to any sub directory or editing the webconfig will cause cause the application to restart.
if so how can i solve this..
thanks in advance.
Well, i've just tested with ASP.NET MVC, it works fine for me.
What i did was craete two actions, one for setting session variable, another for creating file, so i've modified default asp.net mvc application home controller to this:
public ActionResult Index()
{
ViewBag.Message = Session["Sample"];
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult AddSessionVariable()
{
Session["Sample"] = "Sample session variable";
return RedirectToAction("Index");
}
public ActionResult CreateFile()
{
var bmp = new Bitmap(100, 100);
bmp.Save(Server.MapPath(string.Format(#"\Images\{0}", DateTime.Now.Ticks)));
return RedirectToAction("Index");
}
So, when I go to AddSessionVriable, it adds something to session and index action renders that session variable to page, that i could see, that it is not gone. Then I go to create file and my session variable is still there, so that does not restart application. I'm pretty sure, that Web Forms application works the same way, may be you're loosing some exception (for example because of missing permissions) when saving file and that restarts your application.
Don't save uploaded files inside your virtual folder for the web application.
This also reduces the security risk (now, people could potentially upload an asp page, including embedded code, and access it if they can manufacture the URL (which could be dead simple)).