Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multipart POST support #110

Closed
michalkos opened this issue Sep 18, 2014 · 30 comments
Closed

Multipart POST support #110

michalkos opened this issue Sep 18, 2014 · 30 comments

Comments

@michalkos
Copy link

Hello,

do you have any timeframe for Multipart POST?
I would love to use Alamofire, but it's a show stopper for me.

@mattt
Copy link
Sponsor Contributor

mattt commented Sep 18, 2014

Until this is implemented, AFNetworking's multipart form request functionality can be used in conjunction with Alamofire itself.

@mattt mattt closed this as completed Sep 18, 2014
@Jeehut
Copy link

Jeehut commented Oct 5, 2014

I'm going to use AFNetworking for now as suggested, but I'd love to see this in Alamofire as well!
AFNetworking is a lot of overhead just because of one of its many features ... ^^

@db0company
Copy link

Same here. Do you have an idea of when it will be implemented?

@carolanitz
Copy link

same here.I implemented most of my networking with Alamofire and just integrated AFNetworking for the multipart request...I would really love to see this feature implemented and great work so far, thanks!

@ipeisong
Copy link

ipeisong commented Dec 4, 2014

+1

@cnbuff410
Copy link

Would love to have it in Alamofire too

@db0company
Copy link

Here is a quick&dirty patch I use: http://pastebin.com/k9CUJjry
Using AFNetworking works fine though.

@mente
Copy link

mente commented Dec 9, 2014

+1 who wants multipart support

@mente
Copy link

mente commented Dec 9, 2014

@db0company why not make a PR for this?

@db0company
Copy link

@mente Because this is a quick&dirty solution that works for me but might not work for everybody since it's not complete and has hardcoded strings.

@corywilkerson
Copy link

+1 woo and thanks to @db0company - that patch is dope. nyan.

@hsandhu
Copy link

hsandhu commented Jan 19, 2015

@mattt looking to implement this using AFNetworking, any estimate on when it will be implemented in Alamofire?

@tomoyuki28jp
Copy link

I've created a class function to upload single file as multipart/form-data based on this SO answers.

Class

class Photo {
    class func upload(image: UIImage, filename: String) -> Request {
        let route = Router.CreatePhoto()
        var request = route.URLRequest.mutableCopy() as NSMutableURLRequest
        let boundary = "NET-POST-boundary-\(arc4random())-\(arc4random())"
        request.setValue("multipart/form-data;boundary="+boundary,
                         forHTTPHeaderField: "Content-Type")

        let parameters = NSMutableData()
        for s in ["\r\n--\(boundary)\r\n",
                  "Content-Disposition: form-data; name=\"photos[photo]\";" +
                    " filename=\"\(filename)\"\r\n",
                  "Content-Type: image/png\r\n\r\n"] {
            parameters.appendData(s.dataUsingEncoding(NSUTF8StringEncoding)!)
        }
        parameters.appendData(UIImageJPEGRepresentation(image, 1))
        parameters.appendData("\r\n--\(boundary)--\r\n"
                               .dataUsingEncoding(NSUTF8StringEncoding)!)
        return Alamofire.upload(request, parameters)
    }
}

Usage

let rep = (asset as ALAsset).defaultRepresentation()
let ref = rep.fullResolutionImage().takeUnretainedValue()
Photo.upload(UIImage(CGImage: ref)!, filename: rep.filename())
    .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
        println(totalBytesWritten)
    }
    .responseJSON { (request, response, JSON, error) in
        println(JSON)
    }

@matthewchung74
Copy link

@tomoyuki28jp I don't have my head around Alamofire routes yet, can you provide the rest of the code for the Photo example?

@tomoyuki28jp
Copy link

@captainchung Take a look at those SO answers.
http://stackoverflow.com/a/26747857/3958295
http://stackoverflow.com/a/27014372/3958295

@mileswd
Copy link

mileswd commented Apr 19, 2015

@mattt

Until this is implemented, AFNetworking's multipart form request functionality can be used in conjunction with Alamofire itself.

Shortly after you responded (8807fb8), you added this to the README:

Use AFNetworking for any of the following:
[...]
Multipart HTTP request construction

Sorry to bother you, but could you possibly clarify as to whether you still intend to implement this?

@amcuserguy
Copy link

+1

@amcuserguy
Copy link

@tomoyuki28jp

how can i set the params with this input.

PATCH
"/api/accounts/1"
Parameters: {"user"=>
{"first_name"=>"Gretchen",
"last_name"=>"Gapol",
"profile_photo"=>#<ActionDispatch::Http::UploadedFile:0x007fab541ee658 @tempfile=#Tempfile:/var/folders/qn/xhlfpmvd4gq15ycgj2gxqwxh0000gn/T/RackMultipart20150406-372-o4wrif, @original_filename="mocking_jay.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name="user[profile_photo]"; filename="mocking_jay.jpg"\r\nContent-Type: image/jpeg\r\n">}
}

i want to put the image param in "profile_photo"

@cnoon
Copy link
Member

cnoon commented May 3, 2015

@mileswd we are going to implement this. We haven't finalized the 1.3.0 roadmap yet, but most likely this feature will make it onto that list. Stay tuned...

@mileswd
Copy link

mileswd commented May 4, 2015

@cnoon Glad to hear this! Thanks for the update 👍

@nicolas-besnard
Copy link

Any update ?

@ncerezo
Copy link

ncerezo commented May 28, 2015

In the meanwhile I have created a very general solution, based on previous comments and stackoverflow questions.
It does not require Routes just a NSURLRequest.
It allows to add multiple files to the multipart request, as well as other parameters or HTTP headers.
No hardcoded options, no assumptions: you can upload any kind of file, not just photos.

https://gist.github.com/ncerezo/b1991f8dfac01cb162c0

@dyguests
Copy link

http://stackoverflow.com/a/26747857/3958295
It's useful!!!

Thk God. I fixed problem.

@cnoon
Copy link
Member

cnoon commented Jun 22, 2015

Hey everyone, I just put up PR #539 which adds support for MultipartFormData uploads. I would love your feedback before merging it in. Cheers.

@lijy91
Copy link

lijy91 commented Aug 15, 2015

You can try this, it is working

Alamofire.upload(
.POST,
        URLString: "http://blankapp.io/api/v1/update",
        multipartFormData: {
            multipartFormData in
            multipartFormData.appendBodyPart(fileURL: NSURL(fileURLWithPath: imagePath)!, name: "cover")
            multipartFormData.appendBodyPart(data: "Alamofire test title".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: "title")
            multipartFormData.appendBodyPart(data: "test content".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: "content")
            multipartFormData.appendBodyPart(data: "1".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: "type")
        },
        encodingCompletion: {
            encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _ ):
                upload.responseJSON {
                    request, response, JSON, error in
                    println(JSON)
                }
            case .Failure(let encodingError):
                println("Failure")
                println(encodingError)
            }
        }
)

@AshkanImmortal
Copy link

Can you tell how much time (roughly) takes to implement it?

@chrislconover
Copy link

@cnoon: Do you have any tricks up your sleeve for diagnosing stalled uploads? I am logging in progress, the backend in this case is Django Rest Framework on Heroku. What I am seeing is that the upload pauses - my logs stop, and network activity goes to zero. I am running on Wifi and otherwise have good bandwidth.

(Thanks)

@cnoon
Copy link
Member

cnoon commented Oct 15, 2015

Hi @chrisco314, I've seen some weird throttling on uploads on some ISPs before, but generally, it should just upload consistently. Alamofire doesn't do anything to trigger that behavior in any way.

@jkmathew
Copy link

jkmathew commented May 3, 2016

@cnoon :
How can I use public fund upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) method to upload a file with some parameters?

I tried by setting parameters as data for the URLRequest and adding file to multipartFormData, but the server is not getting the parameters and throwing some error.

Is this correct or should I add parameters as data to multipartFormData?

I am using Alamofire.ParameterEncoding.URL for parameter encoding, should I change this to custom and append data with that?

@cnoon
Copy link
Member

cnoon commented May 8, 2016

You need to add the parameters to the multipart form data @johnykutty. 👍🏼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests