MVC中的文件上传-小结
普通Controller实现文件上传
<h2>Upload</h2>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<h4>Select a file:</h4>
<input name="files" id="files" type="file" />
<label id="lbError">@ViewBag.ErrorMessage</label>
<input type="submit" name="submit" value="Upload" />
</div>
}
[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
if (files == null || files.Count() == || files.ToList()[] == null)
{
ViewBag.ErrorMessage = "Please select a file!!";
return View();
}
string filePath = string.Empty;
Guid gid = Guid.NewGuid();
foreach (HttpPostedFileBase file in files)
{
filePath = Path.Combine(HttpContext.Server.MapPath("/Uploads/"), gid.ToString() + Path.GetExtension(file.FileName));
file.SaveAs(filePath);
}
return RedirectToAction("UploadResult", new { filePath = filePath });
}
public ActionResult UploadResult(string filePath)
{
ViewBag.FilePath = filePath;
return View();
}
<system.web>
<httpRuntime maxRequestLength="" executionTimeout="" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="" />
</requestFiltering>
</security>
</system.webServer>
ApiController实现文件上传
通过ApiController来实现文件上传时,不得不参考一下 官方文档了,建议先去阅读一下。
<h2>API Upload</h2>
<form name="apiForm" method="post" enctype="multipart/form-data" action="/api/upload">
<div>
<label for="apifiles">Select a File</label>
<input name="apifiles" type="file" />
</div>
<div>
<input type="submit" value="Upload" />
</div>
</form>
public class UploadController : ApiController
{
public Task<HttpResponseMessage> PostFormData()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new Exception("");
}
string root = HttpContext.Current.Server.MapPath("/Uploads/");
var provider = new ReNameMultipartFormDataStreamProvider(root); var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
string fileName = string.Empty;
foreach (MultipartFileData file in provider.FileData)
{
fileName = file.LocalFileName;
}
//返回上传后的文件全路径
return new HttpResponseMessage() { Content = new StringContent(fileName) };
});
return task;
}
} /// <summary>
/// 重命名上传的文件
/// </summary>
public class ReNameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public ReNameMultipartFormDataStreamProvider(string root)
: base(root)
{ } public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
//截取文件扩展名
string exp = Path.GetExtension(headers.ContentDisposition.FileName.TrimStart('\"').TrimEnd('\"'));
string name = base.GetLocalFileName(headers);
return name + exp;
} }
如上代码,区别与官网给出的.net 4.0 版本的代码的。
MVC中的文件上传-小结的更多相关文章
- spring mvc中的文件上传
使用commons-fileupload上传文件所需要的架包有:commons-fileupload 和common-io两个架包支持,可以到Apache官网下砸. 在配置文件spring-mvc.x ...
- 转:MVC中的文件上传
上传文件与与上传数据区别 上传数据主要指json等简单字符串,上传文件指的是上传word.excel图片等.在上传数据的时候enctype默认为第一个application/x-www-form-ur ...
- ASP.NET MVC下使用文件上传
这里我通过使用uploadify组件来实现异步无刷新多文件上传功能. 1.首先下载组件包uploadify,我这里使用的版本是3.1 2.下载后解压,将组件包拷贝到MVC项目中 3. 根目录下添加新 ...
- [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传
原文 [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传 Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件 ...
- javaWeb中的文件上传下载
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- IIS 7 中设置文件上传大小的方法
在IIS 6.0中设置文件上传大小的方法,就是配置如下节点: <system.web> <httpRuntime maxRequestLength="1918200&quo ...
- 在WebBrowser中通过模拟键盘鼠标操控网页中的文件上传控件(转)
引言 这两天沉迷了Google SketchUp,刚刚玩够,一时兴起,研究了一下WebBrowser. 我在<WebBrowser控件使用技巧分享>一文中曾谈到过“我现在可以通过WebBr ...
- PHP中,文件上传实例
PHP中,文件上传一般是通过move_uploaded_file()来实现的. bool move_uploaded_file ( string filename, string destinati ...
- ASP.NET中的文件上传大小限制的问题
一.文件大小限制的问题 首先我们来说一下如何解决ASP.NET中的文件上传大小限制的问题,我们知道在默认情况下ASP.NET的文件上传大小限制为2M,一般情况下,我们可以采用更改WEB.Config文 ...
随机推荐
- NTP DDOS攻击
客户端系统会ping到NTP服务器来发起时间请求更换,同步通常每隔10分钟发生: 从NTP服务器发回到客户端的数据包可能比初始请求大几百倍.相比之下,通常用于放大攻击中的DNS响应被限制仅为8倍的带宽 ...
- Ajax页面跳转
<script type="text/javascript" > $(document).ready(function () { $(&qu ...
- inline-block元素之间出现间隙
一.问题 这里部分的组成是一个input框和一个a按钮,然后a标签为了设置它的width和height我让他display:inline-block(行内元素以块级元素显示内容).神奇的一幕出现了,两 ...
- Android Butterknife框架配置
一.原理. 最近发现一个很好用的开源框架,蛮不错的,可以简化你的代码,是关于注解的.不多说直接进入使用步骤讲解. 二.步骤. 1.准备阶段,先到官网( http://jakewharton.githu ...
- 去掉搜狗拼音烦人的x+;进入搜狗搜索
- sql server和my sql 命令(语句)的差别,sql server与mysql的比較
sql与mysql的比較 1.连接字符串 sql :Initial Catalog(database)=x; --数据库名称 Data Source(source)=x; ...
- [D3] 6. Color Scale
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...
- linux 进程综合指令
1. 查询当前机器运行的进程总数: ps -ef | wc -l ps -ef | grep httpd | wc -l 2. ulimit命令 表 1. ulimit 参数说明 选项 [option ...
- 3 Ways of JDK Source Code Attachment in Eclipse---reference
You wanna look at a JVM class while you are coding and you cannot. Here is the solution. First of al ...
- MVVM架构的一次实践,重写iOS头条客户端
前言: 一个iOS头条APP,使用MVVM架构实现,代码中有注释,封装了AFN网络请求,解媾代码,使用起来非常方便.用最经典的TableView展示,后续不断更新,喜欢就star或fork一下,有问题 ...