Reputation:
I am using ASP .Net MVC 4.0, vs10
in one of my buttons click event, iam getting company name like this :
if (Request.Form["NAMEbtnImport"].Length > 0)
{
if (Request.Form["NAMEbtnUpload"].Length > 0 && Request.Form["NAMEtxtCompany"].Length > 0 )
{
Session["CompanyName"] = Request.Form["NAMEtxtCompany"].ToString();
var x = collection.GetValue("NAMEbtnUpload");
filePath = x.AttemptedValue.ToString();
filePath = Request.Form["NAMEbtnUpload"];
string fileName = Path.GetFileName(filePath); //var path = Path.Combine(Server.MapPath("~/Uploads"), filePath);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Copy(filePath, Server.MapPath("~/Uploads/" + fileName));
}
companyName = Request.Form["NAMEtxtCompany"].ToString();
newFilePath = "Uploads/" + fileName;
ViewBag.CompanyName = companyName;
}
This is my html : [EDIT]
<input type="file" value="Upload" id="IDbtnUpload" name="NAMEbtnUpload"/>
this is working fine in IE. filepath is full. but in Firefox, only the filename is recieving. Both collection and request.form outputs same data.
what is the problem here? Sorry for my poor english.
Upvotes: 0
Views: 1229
Reputation: 4746
Are you expecting to access the full filepath on the client machine? You shouldn't be able to do this, and should have no need to either.
Browsers allowing this would be a security risk.
Apologies in advance if I have misunderstood what you're trying to do!
EDIT: To handle a file upload in MVC you can use HttpPostedFileBase in your action. Something like this:
<input type="file" name="file">
and
//POST FORM
public ActionResult form_Post(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
file.SaveAs(mySavePath);
}
}
EDIT: and some more code on file saving for your latest comment:
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("/myupload/path/"), fileName);
if (!System.IO.File.Exists(path))
{
file.SaveAs(path);
}
Upvotes: 1
Reputation: 50154
Internet Explorer sends the full file path to the server; Firefox doesn't.
This is a security decision by the browser authors; there's nothing you can do about it.
Furthermore, it looks like you're using File.Copy
to try to copy the source uploaded file to somewhere on the server. This is only made for copying local files - it won't work if the browser isn't running on the server!
You need to use something like
<asp:FileUpload runat="server" ID="fuSample" />
in your aspx
file and
if (fuSample.HasFile)
{
fuSample.SaveAs(
Server.MapPathMapPath("~/Uploads/" + fuSample.FileName));
}
in your codebehind.
Edit: If you're stuck with a vanilla <input type="file" id="someID" ... />
, try
var file = this.Context.Request.Files["someID"];
if (file != null)
file.SaveAs(Server.MapPathMapPath("~/Uploads/" + file.FileName));
Upvotes: 2