WebAPI method that takes a file upload and additional arguments

后端 未结 5 761
野性不改
野性不改 2020-12-04 18:32

I want to upload a file and send along with the file some additional information, let\'s say a string foo and an int bar.

How would I write a ASP.NET WebAPI

5条回答
  •  半阙折子戏
    2020-12-04 19:05

    You can do it by following way : JQuery Method:

        var data = new FormData();
    
        data.append("file", filesToUpload[0].rawFile);
        var doc = {};            
        doc.DocumentId = 0; 
        $.support.cors = true;
        $.ajax({
            url: '/api/document/uploaddocument',
            type: 'POST',
            contentType: 'multipart/form-data',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            success: function (response) {
                docId = response.split('|')[0];
                doc.DocumentId = docId;
                $.post('/api/document/metadata', doc)
                    .done(function (response) {
                    });
              alert('Document save successfully!');
            },
            error: function (e) {
                alert(e);
            }
        });
    

    call your 'UploadDocuement' web api

    [Route("api/document/uploaddocument"), HttpPost]
            [UnhandledExceptionFilter]
            [ActionName("UploadDocument")]
            public Task UploadDocument()
            {
                // Check if the request contains multipart/form-data.
                if (!Request.Content.IsMimeMultipartContent())
                {
                    Task mytask = new Task(delegate()
                    {
                        return new HttpResponseMessage()
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            Content = "In valid file & request content type!".ToStringContent()
                        };
                    });
                    return mytask;
                }
    
    
                string root = HttpContext.Current.Server.MapPath("~/Documents");
                if (System.IO.Directory.Exists(root))
                {
                    System.IO.Directory.CreateDirectory(root);
                }
                var provider = new MultipartFormDataStreamProvider(root);
    
                var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    if (o.IsFaulted || o.IsCanceled)
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);
    
                    FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);
    
                    string guid = Guid.NewGuid().ToString();
    
                    File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));
    
                    string sFileName = provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "");
    
                    FileInfo FInfos = new FileInfo(Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));
    
                    Document dbDoc = new Document()
                    {
                        DocumentID = 0                
    
                    };
    
                    context.DocumentRepository.Insert(dbDoc);
                    context.Save();
    
                    return new HttpResponseMessage()
                    {
                        Content = new StringContent(string.Format("{0}|File uploaded.", dbDoc.DocumentID))
                    };
                }
               );
                return task;
    
            }
    

    Call your metadata web api by following way :

    [Route("api/document/metadata"), HttpPost]
            [ActionName("Metadata")]
            public Task Metadata(Document doc)
            {
                int DocId = Convert.ToInt32(System.Web.HttpContext.Current.Request.Form["DocumentId"].ToString());
    
                Task mytask = new Task(delegate()
                {
                    return new HttpResponseMessage()
                    {
                        Content = new StringContent("metadata updated")
                    };
                });
                return mytask;
            }
    

提交回复
热议问题