views:

137

answers:

1

I have a not-so-ideal situation where uploaded files are stored on an internal network share. So in the database I'm storing the path to where the file was saved, but it's quite possible for the file to get deleted out of sync of the database. So in a Controller action I lookup the upload information and perform checks that things are correct. It can be summed up as something like this:

public ActionResult GetUploadedFile(int uploadId){
    var uploadedFile = Repository<Upload>.FirstOrDefault(upload => upload.ID == uploadID);
    if(uploadedFile == default(Upload)){
        return View("InvalidUpload");
    }
    if(File.Exists(uploadFile.Path)){
        var fileInfo = new FileInfo(uploadFile.Path);
        var contentType = HttpContext.GetMimeTypeForFileInfo(fileInfo) // my lookup extension method
        return File(uploadFile.Path, contentType, uploadFile.Name);
    }
    return View("InvalidUpload");
}

The problem is that this action is currently accessible via a link on a view that is loaded through AJAX. So when the file does exist and everything's OK, it will bring up the standard "What do you want to do with this file" dialog in the browser and keep the content visible to the user. The issue is the other paths through the code. Returning the view takes the user to a completely new URL. And then clicking back will reset where they were (it's basically dynamic jQuery Tabs, so nothing huge, but still still a major inconvience).

So I'm looking for how others may have tackled this situation as it doesn't seem to be uncommon. Or even some feedback to make this a little more user friendly. I don't have a say in where the file is stored, so changing that is not an option.

A: 

There are different types of Action Result that you can use.

Usually when I have a controller method that outputs something other than a view I use a ContentResult action.

public ContentResult GetUploadedFile(int uploadId){

Some result types are:

  1. ViewResult – Represents HTML and markup.
  2. EmptyResult – Represents no result.
  3. RedirectResult – Represents a redirection to a new URL.
  4. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
  5. JavaScriptResult – Represents a JavaScript script.
  6. ContentResult – Represents a text result.
  7. FileContentResult – Represents a downloadable file (with the binary content).
  8. FilePathResult – Represents a downloadable file (with a path).
  9. FileStreamResult – Represents a downloadable file (with a file stream).

List taken from here

Jamie Dixon
if you look at what I have in the question, I'm returning different results. That's not the issue. It's how to handle it on the front-end for better user experience.
Agent_9191