gpt4 book ai didi

C# MVC 文件上传问题

转载 作者:太空宇宙 更新时间:2023-11-03 20:37:44 25 4
gpt4 key购买 nike

我正在尝试将文件上传到我的 mvc 项目中的服务器。我写了我的课,

public class MyModule: IHttpModule

which defines the event

void app_BeginRequest (object sender, EventArgs e)

In it, I check the length of the file that the user has selected to send.

if (context.Request.ContentLength> 4096000)
{
//What should I write here, that file is not loaded? I tried
context.Response.Redirect ("address here");
//but the file is still loaded and then going on Redirect.
}

最佳答案

在 ASP.NET MVC 中,您通常不会编写 http 模块来处理文件上传。您编写 Controller 并在这些 Controller 中编写操作。菲尔·哈克 blogged关于在 ASP.NET MVC 中上传文件:

您有一个包含表单的 View :

<% using (Html.BeginForm("upload", "home", FormMethod.Post, 
new { enctype = "multipart/form-data" })) { %>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />

<input type="submit" />
<% } %>

还有一个 Controller 操作来处理上传:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
if (file.ContentLength > 4096000)
{
return RedirectToAction("FileTooBig");
}
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}

关于C# MVC 文件上传问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4367315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com