0

I'm currently using an external piece of software that I'm trying to plug into my own SaaS. The software has an image upload function and has allowed me to connect it to our Amazon S3 storage and automatically uploads the file there.

However, we want to be able to handle it first and THEN upload afterwards.

The software documentation details this particular function for handling image uploads yourself

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

When I log data.get('file') to the console, before the fetch, it comes out as:

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:""
}

This is the following on the server side:

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

I don't know what parameter the file should be on the server side (to replace byte[] file) to be able to get any further with it.

2 Answers 2

1

You should be trying to get the file from the Request object and not try to pass as a parameter. Here is an example.

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

This is how you call using 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 })
  })
})

Sign up to request clarification or add additional context in comments.

1 Comment

Server side is spot on, but had to change a few things client side. Thanks!
0

Ended up using a POST instead of 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); }
    });

Handler:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.