场景:我最近向我的ASP.NET MVC应用程序添加了一个组件,允许他们将文件上传到数据库中。由于这些文件平均超过2MB,所以我选择使用FILESTREAMs。我将HttpPostedFileBase保存到一个临时文件中,执行一些业务逻辑,然后上传该文件。上传后,用户将被重定向到在浏览器中内联查看文件的页面。以下是相关的上载代码:
var DocContext = new DocumentEntities();
var dbFile = new File
{
DocumentID = Guid.NewGuid(),
Name = fileName,
Type = file.ContentType
};
DocContext.Document.Add(dbFile);
DocContext.SaveChanges();
using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
using (var sqlFS = dbFile.Open(DocContext, FileAccess.Write))
using (var tempFS = tempFile.OpenRead())
{
tempFS.CopyTo(sqlFS);
scope.Complete();
}以下是相关的查看/下载代码:
public ActionResult File(Guid? id = null)
{
if (id == null)
return RedirectToActionPermanent("Index");
return File(DocContext.Document.Find(id.Value) as File);
}
private ActionResult File(File file)
{
if (file == null)
throw new HttpException(404, "Unknown document type");
var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead });
Disposing += d => { scope.Complete(); scope.Dispose(); };
var fs = file.Open(DocContext, FileAccess.Read);
Disposing += d => fs.Dispose();
return new Misc.InlineFileStreamResult(fs, file.MimeType) { FileDownloadName = file.FileName, Inline = true };
}开放方法:
public partial class File
{
public SqlFileStream Open(DocumentEntities db, FileAccess access)
{
var path = db.Database.SqlQuery<string>(
@"SELECT FileData.PathName() FROM [File] WHERE DocumentID = @docID",
new SqlParameter("docID", DocumentID)).First();
var context = db.Database.SqlQuery<byte[]>(
@"SELECT Get_FILESTREAM_TRANSACTION_CONTEXT() FROM [File] WHERE DocumentID = @docID",
new SqlParameter("docID", DocumentID)).First();
return new SqlFileStream(path, context, access);
}
}查看以前上传的文件的工作得很好。查看用户自己上传的文件(最近?),出现以下异常: The transaction operation cannot be performed because there are pending requests working on this transaction.
到底怎么回事?
更新:我认为因为我是一个SQL系统管理员,所以我可以上传文件并查看它们。
发布于 2015-01-22 20:31:26
当数据库条目具有MIME类型而不是type列中的扩展名时,我使用IIS和web.config推断要给文件提供什么扩展名。但是普通用户没有读取web.config的权限。因此,当非服务器管理员用户试图查看以MIME类型而不是扩展名存储的文件时,我的例程会抛出一个权限异常,这将以某种方式触发事务操作异常。不知道怎么做。
https://stackoverflow.com/questions/28057048
复制相似问题