Rik*_*iki 7 c# ajax asp.net-web-api
我想通过进行ajax调用使用WebApi上传文件,文件将保存到数据库中.我尝试了这个链接中给出的代码 .在这里,它将收到的数据保存为硬盘驱动器,作为没有指定扩展名的文件,但我想做一些事情,比如我将文件保存到数据库时我也希望保存文件名和扩展名,如果我需要的话下载文件我可以提供文件名和扩展名.在链接中,文件作为文件保存到硬盘驱动器,但有任何方法可以直接将文件保存到DB.
Jot*_*aBe 15
答案有几个部分.
首先,要上传文件,您可以使用包含以下代码的视图:
@using (Html.BeginForm())
{
<input type="file" value="Choose a file"/>
<br/>
<input type="button" value="Upload" id="upload"/>
}
@section scripts
{
<script type="text/javascript">
$(document).ready(function() {
$('#upload').click(function () {
var data = new FormData();
var file = $('form input[type=file]')[0].files[0];
data.append('file',file);
$.ajax({
url: '/Api/File/Upload',
processData: false,
contentType: false,
data: data,
type: 'POST'
}).done(function(result) {
alert(result);
}).fail(function(a, b, c) {
console.log(a, b, c);
});
});
});
</script>
}
Run Code Online (Sandbox Code Playgroud)
其次,要接收此数据,请使用以下方法创建控制器:
public class FileController : ApiController
{
[HttpPost]
public async Task<string> Upload()
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
// extract file name and file contents
var fileNameParam = provider.Contents[0].Headers.ContentDisposition.Parameters
.FirstOrDefault(p => p.Name.ToLower() == "filename");
string fileName = (fileNameParam == null) ? "" : fileNameParam.Value.Trim('"');
byte[] file = await provider.Contents[0].ReadAsByteArrayAsync();
// Here you can use EF with an entity with a byte[] property, or
// an stored procedure with a varbinary parameter to insert the
// data into the DB
var result
= string.Format("Received '{0}' with length: {1}", fileName, file.Length);
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
第三,默认情况下,最大上传大小是有限的.您可以克服此限制修改web.config:
添加maxRequestLength="max size in bytes"在<configuration><system.web><httpRuntime>.(或者如果它不存在则创建这个元素):
添加maxAllowedContentLength到<configuration><system.web><security><requestFiltering><requestLimits>元素(如果不存在,则创建此元素)
这些条目如下所示:
<configuration>
<system.web>
<!-- kilobytes -->
<httpRuntime targetFramework="4.5" maxRequestLength="2000000" />
<configuration>
<system.webServer>
<security>
<requestFiltering>
<!-- bytes -->
<requestLimits maxAllowedContentLength="2000000000"/>
Run Code Online (Sandbox Code Playgroud)
注意:您应该将其包含在<location>元素中,以便此限制仅应用于上载文件的特定路径,如下所示:
<location path="Api/File/Upload">
<system.web>
...
<system.webServer>
...
Run Code Online (Sandbox Code Playgroud)
注意修改根目录web.config,而不是Views文件夹中的根目录.
第四,关于在数据库中保存数据,如果使用EF,您只需要这样的实体:
public class File
{
public int FileId { get; set; }
public string FileName { get; set; }
public byte[] FileContent { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
创建此类的新对象,添加到上下文并保存更改.
如果使用存储过程,请创建一个具有varbinary参数的存储过程,并传递byte[] fileas值.
| 归档时间: |
|
| 查看次数: |
19992 次 |
| 最近记录: |