如何在asp.net mvc 3中取消和删除上传文件?

时间:2011-10-11 17:09:42

标签: asp.net asp.net-mvc-3 file-upload

我正在使用文件流在我的控制器中接收一个大文件。代码如下:

[HttpPost]
public JsonResult Create(string qqfile, Attachment attachment)
{
    Stream inputStream = HttpContext.Request.InputStream;
    string fullName = ingestPath + Path.GetFileName(qqfile);


    using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
    {
        try
        {
            var buffer = new byte[1024];

            int l = inputStream.Read(buffer, 0, 1024);
            while (l > 0)
            {
                fs.Write(buffer, 0, l);
                l = inputStream.Read(buffer, 0, 1024);
            }
            return Json(new {success = "true"});
        }
        catch (Exception)
        {
            return Json(new {success = "false"});
        }
        finally
        {
            inputStream.Flush();
            inputStream.Close();

            fs.Flush();
            fs.Close();
        }
    }
}

在我的页面ajax方法中,我添加了一个按钮来取消文件上传并从磁盘中删除未完成的文件。对名为“取消”的操作的ajax请求:

        [HttpPost]
    public JsonResult Cancel(string filename)
    {
        string localName = HttpUtility.UrlDecode(filename);
        string fullName = ingestPath + Path.GetFileName(localName);
        if (System.IO.File.Exists(fullName))
        {
            System.IO.File.Delete(fullName);
        }
        return Json(new {cancle = true});
    }

问题是:文件无法删除,异常消息为

  

该进程无法访问文件'e:\ tempdata \ filename_xxx.xxx',因为它正在被其他进程使用。

我认为是因为这个文件的文件流没有关闭。如何在“取消”操作中关闭此文件流并删除文件?

-

OH!我找到了一种方法来解决它。

using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))

这很简单,只需声明一个fileshare属性:FileShare.Delete

using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write, FileShare.Delete))

我花了4个小时来谷歌并调试和测试并尝试解决它。我问了stackoverflow后10分钟,我自己得到了答案。有趣!并希望它对某些人也有用。

1 个答案:

答案 0 :(得分:0)

您可以将该文件流放入会话中,然后在取消操作中使用该会话来关闭流。