2

I have file uploads working great on an ASP MVC3 web site. Currently the files are saved in a folder on the web site called "Files". Users can upload any type of file (e.g. myphoto.jpg, mydocument.docx, etc).

When a user uploads a file I store information about the file in a SQL database and who uploaded it etc.

My questions:

  1. How do I intercept a GET request to a file URL (e.g. /Files/myphoto.jpg) to see if the user is allowed to view that file? (based on their rights in the application)? I don't like the idea of writing a route constraint to check the database before allowing access.
  2. Ideally I'd like to store the files in a different location than the web site file location, but somewhere where the website can determine the file and it's location from the request, yet serve it up as if it was at the location requested (correct content-type headers etc).
4

2 回答 2

5

您可以添加一个控制器来服务器文件。

public class FileController : Controller
{

    private IFileStore _fileStore;

    public FileController(IFileStrore fileStore)
    {
        this._fileStore = fileStore; 
    }

    public ActionResult Index(string fileName)
    {
        // Do a database look up if the user has permission
        if (_fileStore.HasPermission(fileName, User))
        {
            // Flush the file content if the user has permission
            var myfile = _fileStore.GetFile(fileName);
            Response.ClearContent();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.FileName);
            Response.AddHeader("Content-Length", myfile.Length.ToString());

            Response.ContentType = myfile.Extension.ToLower();
            Response.WriteFile(myfile.FullName, false);
            Response.Flush();
            Response.Close();
        }
        else
        {
            // Return a Access Denied page
            return View("NoPermission");
        }
    }

}
于 2012-07-31T08:42:32.193 回答
0

您可以在 web.config 中设置它:

<!-- This section gives the authenticated user with myRole role access to all of the files that are stored in the images folder.  -->
<location path="images">
   <system.web>
     <authorization>
    <allow users =".\myRole" />
     </authorization>
   </system.web>
</location>

http://msdn.microsoft.com/en-us/library/8d82143t

于 2012-07-31T10:06:56.470 回答