文件上传在MVC(File upload in MVC)

2019-08-31 09:09发布

我试图内MVC上传文件。 我看到的大多数解决方案,以便为使用网络表单。 我不想使用和personly喜欢使用流。 你如何在MVC实现REST风格的文件上传? 谢谢!

Answer 1:

编辑:而当你认为你拥有这一切想通了,你知道,有一个更好的办法。 退房http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

原文:我不知道,我明白你的问题100%,但我认为你要上传文件到一个URL,看起来像HTTP:// {服务器名称} / {}控制器/上传? 这将实现完全一样使用Web表单一个正常的文件上传。

所以,你的控制器有一个名为上传动作,看起来与此类似:

//For MVC ver 2 use:
[HttpPost]
//For MVC ver 1 use:
//[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Upload()
{
    try
    {
        foreach (HttpPostedFile file in Request.Files)
        {
            //Save to a file
            file.SaveAs(Path.Combine("C:\\File_Store\\", Path.GetFileName(file.FileName)));

            // * OR *
            //Use file.InputStream to access the uploaded file as a stream
            byte[] buffer = new byte[1024];
            int read = file.InputStream.Read(buffer, 0, buffer.Length);
            while (read > 0)
            {
                //do stuff with the buffer
                read = file.InputStream.Read(buffer, 0, buffer.Length);
            }
        }
        return Json(new { Result = "Complete" });
    }
    catch (Exception)
    {
        return Json(new { Result = "Error" });
    }
}

在这种情况下,我回到JSON来表示成功,但如果需要的话,你可以将其更改为XML(或任何为此事)。



Answer 2:

public ActionResult register(FormCollection collection, HttpPostedFileBase FileUpload1){
RegistrationIMG regimg = new RegistrationIMG();
string ext = Path.GetExtension(FileUpload1.FileName);
string path = Server.MapPath("~/image/");
FileUpload1.SaveAs(path + reg.email + ext);
regimg.Image = @Url.Content("~/image/" + reg.email + ext);
db.SaveChanges();}


文章来源: File upload in MVC