简体   繁体   中英

Cannot find path using FileUpload ASP.NET C#

FileUpload objControl = (FileUpload)Page.Form.FindControl("cphMain").FindControl(sColumnName);
//check if file upload has a file name before saving
if (objControl.HasFile)
{
   sSingleValue = Path.GetFileName(objControl.PostedFile.FileName);
                            uploadFiles.Add(sColumnName, objControl);
   fStream = File.OpenRead(Path.GetFullPath(objControl.PostedFile.FileName));
   contents = new byte[fStream.Length];
   fStream.Read(contents, 0, (int)fStream.Length);
   fStream.Close();
 }
 else
 {
   blInclude = false;
 }

Im using the code above to take a pdf file from the fileupload and convert it to bytes which I will then use to save the file to a SQL DB. When the site is deployed to a server and I am accessing it on my machine its giving me an error (but its running fine on a dev machine where I am running locally)

If I change the code to upload the file into the website directory the pdf is being written to the database containing all zeros.

Exception information: Exception type: DirectoryNotFoundException Exception message: Could not find a part of the path 'c:\\users\\gavin\\documents\\test.pdf'

Any help appreciated

You're attempting to do a File.OpenRead on a file path that is A.) most likely only the filename because the file upload doesn't contain the path and B.) even if the FileName did have the file path it would be local to your machine, but this code is running on the server and therefore can't access that path anyway. It works when you run it locally because the server and the machine you're uploading from are the same.

You don't need to do any of this anyway. The PostedFile property of the upload control has an InputStream that contains the bytes of the file. http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.inputstream(v=vs.110).aspx

if (objControl.HasFile)
{
   sSingleValue = Path.GetFileName(objControl.PostedFile.FileName);
   uploadFiles.Add(sColumnName, objControl);   
   contents = new byte[objControl.PostedFile.InputStream.Length];
   objControl.PostedFile.InputStream.Read(contents, 0, 
       (int)objControl.PostedFile.InputStream.Length);
}

Make Sure you have full permission to do those activities on a physical path that corresponds to the virtual directory. Give permission for the following group -"IIS_IUSRS".That user will need Create / Write / Modify permissions to the corresponding physical path.If the users doesn't have enough permission,He can't do any operations like Create/Read/Write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM