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



我目前正在使用一个外部软件,我正在尝试将其插入到我自己的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(以便能够进一步使用它。

您应该尝试从请求对象获取文件,而不是尝试作为参数传递。下面是一个示例。

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 进行调用的方式。

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

最终使用 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");
}

相关内容

  • 没有找到相关文章

最新更新