如何在web api中上传图片

时间:2016-07-09 05:59:02

标签: jquery asp.net-web-api

我在web api的一个项目中工作。我在api / App_Data文件夹的图像中遇到了一些问题。

我的观看代码如下

    <form data-bind="submit: uploadApi">
        <div>
            <label for="caption">Image Caption</label>

        </div>
        <div>
            <label for="image1" >Image File</label>
            <input name="image1" type="file"  data-bind="value: imgPath" />
        </div>
        <div>
            <input type="submit" value="Submit" />
        </div>
    </form>
</div>

我的jquery代码如下

 self.uploadApi = function () {
  /*  var data = {
        imgpath: self.imgPath()
    };
    alert(self.imgPath());*/



    var data = new FormData();
    var file = self.imgPath();
    data.append('file', file);

    $.ajax({
        type: 'POST',
        url: '/api/Upload',
        processData: false,
       // contentType: 'application/json; charset=utf-8',
       // data: JSON.stringify(data)
        contentType: false,
        data:data
    }).done(function (data) {
        self.result("Done!");
    }).fail(showError);



} 

控制器如下

  public async Task<string> PostFormData()
    {





        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;










    }

但我无法上传图片

1 个答案:

答案 0 :(得分:0)

您正以错误的方式构建FormData。其中一个选项是:

var form = $('form')[0];
var formData = new FormData(form); //it will already include the selected file