1

I am trying to post a file to a web API from Swift. The request I send is received fine, but it doesn't have any file in it. I was able to peek at request from the C# controller and HttpContext.Current.Request.Files.Count is 0. I suspect that instead of attaching a file to the body of the request, it just puts in the file's contents as raw data.

Code creating request:

func upload(_ fileName:URL)
{
    let requestUrl:URL = URL(string: uploadURL)!
    let request = NSMutableURLRequest(url: requestUrl)
    request.httpMethod = "POST"
    request.httpBodyStream = InputStream(url: fileName)

    let (data, response, error) = URLSession.shared.synchronousDataTaskWithRequest(request as URLRequest)
}

What am I doing wrong?

If it is helpful to understand what kind of request I am trying to build, this is the working code in JS which creates a FormData object from an HTML <input type='file'> element:

$.ajax({
    url: $('#apiURL').val() + 'Upload'
    type: 'POST',
    contentType: false,
    processData: false,
    data: new FormData($('form')[0]),
    success: function (data)
    {
        // doing successful things
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        alert("Failed");
    }
});

I basically just want to send a file to the same controller it references but in swift...

Conner
  • 352
  • 4
  • 10
  • Maybe try adding the file in the form of `NSData`? Like the following: `request.HTTPBody = NSData(contentsOfFile: expandedPath)` – Tony Apr 19 '18 at 17:37
  • Maybe use `Data(contentsOf: path)` instead – Tony Apr 19 '18 at 17:45

1 Answers1

1

My google-fu wasn't up to par. Copy-paste of the answer given with minor code changes to work with the data types I already had made it work: https://stackoverflow.com/a/26163136/6825722

Conner
  • 352
  • 4
  • 10