如何处理从jQuery上传图像到ASP.Net Web服务?

时间:2017-11-10 15:20:13

标签: jquery asp.net web-services

我目前正在使用外部软件,我正试图插入我自己的SaaS。该软件具有图像上传功能,允许我将其连接到我们的Amazon S3存储,并自动将文件上传到那里。

但是,我们希望能够先处理它,然后再上传。

软件文档详细说明了此特定功能,用于自行处理图像上传

editor.registerCallback('image', function(file, done) {
    var data = new FormData()
  data.append('file', file.accepted[0])

  fetch('/Webservices/MyService.asmx/UploadImage', {
    method: 'POST',
    headers: {
      'Accept': 'application/json'
    },
    body: data
  }).then(response => {
    // Make sure the response was valid
    if (response.status >= 200 && response.status < 300) {
      return response
    } else {
      var error = new Error(response.statusText)
      error.response = response
      throw error
    }
  }).then(response => {
    return response.json()
  }).then(data => {
    // Pass the URL back mark this upload as completed
    callback({ progress: 100, url: data.filelink })
  })
})

当我将data.get('file')记录到控制台时,在获取之前,它会显示为:

File(36071)
{
  lastModified :1510142017134
  lastModifiedDate: Wed Nov 08 2017 11:53:37 GMT+0000 (GMT Standard Time) {}
  name: "477.gif"
  size :36071
  type: "image/gif"
  webkitRelativePath:""
}

服务器端如下:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public string UploadImage(byte[] file)
{
   return "hello";
}

我不知道文件在服务器端应该是什么参数(替换byte[] file)以便能够进一步使用它。

2 个答案:

答案 0 :(得分:1)

您应该尝试从Request对象获取文件,而不是尝试作为参数传递。 这是一个例子。

public class MyService : IHttpHandler
{
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.Files.AllKeys.Any())
        {
            // Get the uploaded image from the Files collection
            var httpPostedFile = context.Request.Files[0];


            string fileFullName = Path.Combine(HttpContext.Current.Server.MapPath("~/content"), httpPostedFile.FileName);
            httpPostedFile.SaveAs(fileFullName);
        }

        context.Response.ContentType = "text/plain";
        context.Response.Write("Success");
    }
}

这是你使用JQuery调用的方式。

&#13;
&#13;
editor.registerCallback('image', function(file, done) {
    var data = new FormData()
  data.append('file', file.accepted[0])

  fetch('/Webservices/MyService.ashx', {
    method: 'POST',
    body: data,
	processData: false, // tell jQuery not to process the data
	contentType: false, // tell jQuery not to set contentType
  }).then(response => {
    // Make sure the response was valid
    if (response.status >= 200 && response.status < 300) {
      return response
    } else {
      var error = new Error(response.statusText)
      error.response = response
      throw error
    }
  }).then(response => {
    return response.json()
  }).then(data => {
    // Pass the URL back mark this upload as completed
    callback({ progress: 100, url: data.filelink })
  })
})
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用POST而不是FETCH结束。

var formData = new FormData();
    formData.append('file', file.accepted[0]);

    $.ajax({
        type: "POST",
        url: "EditorImageUpload.ashx",
        data: formData,
        processData: false,
        cache: false,
        contentType: false,
        success: function (val) {
            console.log('success'); done({
                progress: 100, url: val}); },
        error: function (val) { console.log('post fail'); console.log(val); }
    });

处理程序:

public void ProcessRequest(HttpContext context)
{
    if (context.Request.Files.AllKeys.Any())
    {
        // Get the uploaded image from the Files collection
        var httpPostedFile = context.Request.Files[0];

        //do stuff with file
    }

    context.Response.ContentType = "text/plain";
    context.Response.Write("Success");
}