使用上传文件的WebAPI,阿贾克斯 [英] Upload file using WebApi, ajax

查看:143
本文介绍了使用上传文件的WebAPI,阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一个Ajax调用该文件将保存到数据库中使用的WebAPI上传文件。我试图在给定的code
<一href=\"http://stackoverflow.com/questions/17177237/webapi-ajax-formdata-upload-with-extra-parameters\">this链接 。在这里,它被保存接收到的数据到硬盘驱动器为没有指定扩展名的文件,但我想要做的事,当我将文件保存到数据库就像我也想以后保存文件名和扩展名的事业,如果我需要要下载的文件,我可以提供文件名和扩展它。而在链接文件被保存到硬盘驱动器上的文件,但有什么办法,我可以直接将文件保存到数据库中。

I want to upload file using a WebApi by making an ajax call and the file will save into database. I tried the code given in the this link. Here, it is saved the received data to hard drive as a file with no extension specified but I want to do something like when I'm saving the file to Database I also want to save the file name and the extension cause later if I need to download the file I can provide the file name and extension with it. And in the link the file is saved to hard drive as a file but is there any way that I can directly save the file to DB.

推荐答案

答案有几个部分。

首先,要上传的文件,你可以使用一个视图与code是这样的:

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

@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>    
}

二,接收这个数据,创建一个控制器,用这样的方法:

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

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;
    }
}

三,默认最大上传大小限制。你可以克服这个限制修改的web.config


  1. 添加在的maxRequestLength =的最大字节大小 &LT;结构&gt;&LT;的System.Web&GT;&LT;的httpRuntime&GT; 。 (或创建此字元素,如果不存在的话):

  1. Add maxRequestLength="max size in bytes" in <configuration><system.web><httpRuntime>. (Or create this lement if it doesn't exist):

添加 maxAllowedContentLength 来<$c$c><configuration><system.web><security><requestFiltering><requestLimits>元素(或创建这个元素,如果不存在的话)

Add maxAllowedContentLength to <configuration><system.web><security><requestFiltering><requestLimits> element (or create this element if it doesn't exist)

这些条目是这样的:

<configuration>
  <system.web>
    <httpRuntime targetFramework="4.5" maxRequestLength="2000000000" />

<configuration>
  <system.web>
   <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="2000000000"/>

谨防修改根的web.config ,而不是一个在查看文件夹中。

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

第四,节省了数据库中的数据,如果使用EF,你只需要一个这样的实体:

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.

如果您使用存储过程,创建一个具有 VARBINARY 参数,并通过字节[]文件作为价值。

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

这篇关于使用上传文件的WebAPI,阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆