Upload file using WebApi, ajax

后端 未结 6 1172
深忆病人
深忆病人 2020-12-06 02:39

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 da

6条回答
  •  佛祖请我去吃肉
    2020-12-06 03:42

    The answer has several parts.

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

    @using (Html.BeginForm())
    {
        
        
    } @section scripts { }

    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:

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

    2. 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.

提交回复
热议问题