Giter VIP home page Giter VIP logo

Comments (12)

idoodler avatar idoodler commented on May 5, 2024

Hi elepone,

i faced the same task, and I had no idea how to solve it. I then used Postman to debug and learn about these multipart/form-data stuff.

And here is the code I came up with. I have no idea if it works everywhere, and If I parse everything correctly. Please have a look and tell me if it is working for you!

This is written in Swift 2.0, so it may not work for you without some modifications

If you want to send multipart/form-data via Javascript: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_forms_through_JavaScript

server["/setFile"] = { request in
    guard request.method.uppercaseString == "POST" else {
        return .OK(.JSON(["response" : ["statuscode" : HttpResponse.Forbidden.statusCode(), "statusmessage" : HttpResponse.Forbidden.reasonPhrase(), "message" : "\"\(request.method.uppercaseString)\" is not supported, please use \"POST\""]]))
    }
    guard !request.body!.isEmpty else {
        return .OK(.JSON(["response" : ["statuscode" : HttpResponse.Forbidden.statusCode(), "statusmessage" : HttpResponse.Forbidden.reasonPhrase(), "message" : "It looks like the body is empty!"]]))
    }

    // Relevant part!!!
    let bodyComponents = request.body?.componentsSeparatedByString("\r\n") // We seperate every line...
    let seperator = bodyComponents!.first! // This is always the seperator!
    var files: [String] = (request.body?.componentsSeparatedByString(seperator))! // These are the file(s)
    files.removeLast() // Under the last seperator is just a "\r\n", so we can remove it...
    for postFile in files { // We then iterate over files
        if !postFile.isEmpty { // we check if the posted file part of the POST Header is empty (Just to make sure)
            if let (mayData, fileName, contentType) = dataFromFormDataPost(postFile) { // We then parse out the Data as NSData, Filename as String and the contentType as String dataFromFormDataPost(headerBodyPart: String!) returns a tuple thats optional, so we unwrap it!
                if let data = mayData { // We unwrap data from the unwrapped tuple
                    // Here you can do what ever you want with your NSData!
                    let newFilePath = "/".stringByAppendingPathComponent(fileName)
                    if data.writeToFile(newFilePath, atomically: true) {
                        return .OK(.JSON(["response" : ["statuscode" : HttpResponse.OK(.HTML("")).statusCode(), "statusmessage" : HttpResponse.OK(.HTML("")).reasonPhrase(), "message" : "Got file \"\(fileName)\""]]))
                    } else {
                        return .OK(.JSON(["response" : ["statuscode" : HttpResponse.InternalServerError.statusCode(), "statusmessage" : HttpResponse.InternalServerError.reasonPhrase(), "message" : "Can't save \"\(fileName)\".", "info" : ["fileName" : fileName]]]))
                    }
                } else {
                    return .OK(.JSON(["response" : ["statuscode" : HttpResponse.BadRequest.statusCode(), "statusmessage" : HttpResponse.BadRequest.reasonPhrase(), "message" : "Got file \"\(fileName)\" with invalide data!", "info" : ["fileName" : fileName]]]))
                }
            } else {
                return .OK(.JSON(["response" : ["statuscode" : HttpResponse.BadRequest.statusCode(), "statusmessage" : HttpResponse.BadRequest.reasonPhrase(), "message" : "Something went wrong or the Content-Type is not supported"]]))
            }
        }
    }
    return .OK(.JSON(["response" : ["statuscode" : HttpResponse.InternalServerError.statusCode(), "statusmessage" : HttpResponse.InternalServerError.reasonPhrase(), "message" : "Error setting fileContent"]]))
}

private func dataFromFormDataPost(headerBodyPart: String!) -> (data: NSData?, fileName: String, contentType: String)? {
    // This should explain itselfe I think, and I hope this is the right way to get the data:)
    var headerBodyPartComponents = headerBodyPart.componentsSeparatedByString("\r\n")
    let contentDisposition = headerBodyPartComponents[1]
    let contentDispositionComponents = contentDisposition.stringByReplacingOccurrencesOfString("Content-Disposition: ", withString: "").componentsSeparatedByString("; ")
    var fileName = ""
    for item in contentDispositionComponents {
        if item.hasPrefix("filename=") {
            fileName = item.stringByReplacingOccurrencesOfString("\"", withString: "").stringByReplacingOccurrencesOfString("filename=", withString: "")
            break
        }
    }
    let contentType = headerBodyPartComponents[2].stringByReplacingOccurrencesOfString("Content-Type: ", withString: "")
    headerBodyPartComponents.removeAtIndex(0)
    headerBodyPartComponents.removeAtIndex(0)
    headerBodyPartComponents.removeLast()
    let data = headerBodyPartComponents.last?.data()
    if data != nil {
        return (data, fileName, contentType)
    }
    return nil
}

from swifter.

damian-kolakowski avatar damian-kolakowski commented on May 5, 2024

I added support for 'application/x-www-form-urlencoded' ( f8aec28 ).
'multipart/form-data' is on the way.

from swifter.

IvanMathy avatar IvanMathy commented on May 5, 2024

Hey @glock45,

Is there any news on this? I would love to help implement it!

I_

from swifter.

damian-kolakowski avatar damian-kolakowski commented on May 5, 2024

@IvanMathy hi man :) here is an example of the multipart request.

POST / HTTP/1.1
Host: localhost:8000
Content-Type: multipart/form-data; boundary=90519140415
Content-Length: 554

--90519140415
Content-Disposition: form-data; name="part1"

Hello
--90519140415
Content-Disposition: form-data; name="part2"; filename="part2.txt"
Content-Type: text/plain

Multi
--90519140415
Content-Disposition: form-data; name="part3"; filename="part3.html"
Content-Type: text/html

Part
--90519140415-

from swifter.

IvanMathy avatar IvanMathy commented on May 5, 2024

Thank you! iDoodler's answer gave me some pretty good pointers as well, I might do a PR soon.

from swifter.

VFUC avatar VFUC commented on May 5, 2024

FYI, I'm also working on this over at my fork, handling of metadata and multiple files is WIP but the basic extraction of data as NSData object works.

from swifter.

damian-kolakowski avatar damian-kolakowski commented on May 5, 2024

@VFUC thanks man. I will have a look.

from swifter.

 avatar commented on May 5, 2024

I have the same problem,I don't know how to receive a post request,give me a hand,think you ( and a html file? :D

from swifter.

damian-kolakowski avatar damian-kolakowski commented on May 5, 2024

@SmilingXinyi there is an example in the source code. Please have a look at:

HTML Page: https://github.com/glock45/swifter/blob/master/Resources/login.html

best
dk

from swifter.

 avatar commented on May 5, 2024

Thank you
I want to upload a PDF file to iOS device,when i have a post request,can't receive the file data.
I don't know how to receive the data

from swifter.

damian-kolakowski avatar damian-kolakowski commented on May 5, 2024

Ok. We added support for multipart POST requests ( 8ec765f ). I will put an example here when I finish with merges.

from swifter.

damian-kolakowski avatar damian-kolakowski commented on May 5, 2024

hi @elepone @IvanMathy @VFUC @SmilingXinyi

please have a look at the example: https://github.com/glock45/swifter/blob/master/Sources/DemoServer.swift#L58

html web page: https://github.com/glock45/swifter/blob/master/Resources/file.html

best
dk

from swifter.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.