webapi实现AJAX多文件上传,c# - Upload file using WebApi, ajax - Stack Overflow

The answer has several parts.

First, to upload the file, you can use a view with code like this:

@using (Html.BeginForm())

{

}

@section scripts

{

$(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);

});

});

});

}

Second, to receive this data, create a controller, with a method like this:

public class FileController : ApiController

{

[HttpPost]

public async Task 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;

}

}

Third, by default the maximum upload size is limited. You can overcome this limitations modifying web.config:

Add maxRequestLength="max size in bytes" in . (Or create this lement if it doesn't exist):

Add maxAllowedContentLength to element (or create this element if it doesn't exist)

These entries look like this:

NOTE: you should include this inside a element, so that this limits are only applied to the particular route where the files are uploaded, like this:

...

...

Beware to modify the root web.config, not the one in the Views folder.

Fourth, as to saving the data in the database, if you use EF, you simply need an entity like this:

public class File

{

public int FileId { get; set; }

public string FileName { get; set; }

public byte[] FileContent { get; set; }

}

Create a new object of this class, add to the context and save changes.

If you use stored procedures, create one which has a varbinary parameter, and pass the byte[] file as value.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值