开发者

Attempting to open a user-specified file and process it, path is lost

So, I'm working on my first ASP.NET MVC 3 application and one thing I need to do is handle some data that is exported from someone else's syst开发者_高级运维em and turn around and import it, on user action, into the system and perform some error checking, etc. on it.

Here's how I have attempted to solve this issue:

I've got a view with a div:

<div>
   <span><b>Recipe Data:</b>
     <input type="file" name="uploadFile" />
     <input type="submit" value="Load" />
   </span>
</div>

and that allows me to choose a file and then submit it. Then I've got a controller action that looks like this:

[HttpPost]
public ActionResult Index(HttpPostedFileBase uploadFile)
{
   try
   {
      // attempt to read the file
   }
   catch (Exception)
   {
      throw;
   }
}

So, when I'm using IE, I can examine the uploadFile parameter and it gives me a path like:

FileName:c:\\Users\\Matt\\Desktop\\TestFiles\\AppleBerry.xml

(which is exactly the full path to the file I picked)

But when I try the same thing in FireFox, that path is stripped off, so uploadFile.FileName is just AppleBerry.xml and the XDocument.Load tries to load it from:

C:\Program Files (x86)\Common files\Microsoft Shared\DevServer\10.0\AppleBerry.xml

So, I'm pretty sure that I'm going about this the wrong way and need some guidance. I need to read in that XML file, preferably via XDocument.Load() and then do some checks and eventually push the records in that xml file into a DB table. The only part I'm having issues with is this file path. Any help you can provide with this would be most appreciated.


Try loading the file directly from the request stream and don't rely on the FileName property because you haven't saved the file on the server yet so it won't find it:

[HttpPost]
public ActionResult Index(HttpPostedFileBase uploadFile)
{
    if (uploadFile != null && uploadFile.ContentLength > 0)
    {
        try
        {
            // attempt to read the file
            var doc = XDocument.Load(uploadFile.InputStream);
            // TODO: do something with the XML document
        }
        catch (Exception)
        {
            // Make sure you do something more meaningful here
            // instead of rethrowing and erasing the stacktrace 
            throw;
        }
    }
    else
    {
        // The user didn't upload any file => take respective actions
    }
}


The server does not have access to the client's file system so the original path is irrelevant. Furthermore the file is not saved onto the server file system, so you should be loading it from the InputStream property, as per Darin's answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜