本文介绍了如何取消和删除asp.net MVC 3上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是FILESTREAM接受我的控制器的大文件。低于codeS:

I am using a filestream to receive a large file in my controller. codes below:

[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请求到名为取消的操作:

And in my page ajax method, I add a button to cancel the file uploading and delete the unfinished file from disk. The ajax request to the action named "Cancel":

        [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});
    }

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

The problem is: the file can not delete, and the exception message is

该进程无法访问文件'E:\\ TempData的\\ filename_xxx.xxx'because它正被另一个进程使用

我想这是因为,该文件的文件流没有关闭。如何关闭这个文件流,在我的取消操作删除文件?

I think it is because that ,the filestream of this file is not closed. How can I close this filestream and delete the file in my 'Cancel' action?

-

OH!我发现了一个方法,现在解决这个问题。

OH! I found a method to resolve it now.

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

这是简单,只要申报文件共享属性:FileShare.Delete

It is to simple, just declaration a fileshare property: FileShare.Delete

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

我花了4个小时谷歌和调试和测试,并试图解决它。仅仅10分钟后,我问计算器,我自己得到了答案。有趣!并希望它是一个人太有用了。

I spent 4 hours to google and debug and test and try to resolve it. Just 10 mins after I asked stackoverflow, I got the answer by myself. Interesting! And hope it is useful to someone too.

推荐答案

您可以把该文件流在一个会话,然后使用该会话在取消操作来关闭流。

You could put that file stream in a session then use that session in your cancel action to close the stream.

这篇关于如何取消和删除asp.net MVC 3上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:52