Comments (12)
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.
I added support for 'application/x-www-form-urlencoded' ( f8aec28 ).
'multipart/form-data' is on the way.
from swifter.
Hey @glock45,
Is there any news on this? I would love to help implement it!
I_
from swifter.
@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.
Thank you! iDoodler's answer gave me some pretty good pointers as well, I might do a PR soon.
from swifter.
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.
@VFUC thanks man. I will have a look.
from swifter.
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.
@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.
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.
Ok. We added support for multipart POST requests ( 8ec765f ). I will put an example here when I finish with merges.
from swifter.
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)
- websocket sometimes not working in macOS sandbox app HOT 1
- LICENSE file contains placeholder text.
- usleep degrades when using Swifter
- Unable to connect to server HOT 1
- tvOS 16 Beta 2 Unable to override the Stub that has same url
- Builds fails when trying to use `Swifter` in XCUITest HOT 3
- 404 Not Found HOT 1
- Building release is extremely slow
- Enhancement request: Swifter to label .wasm files as "application/wasm" when it serves them
- Can the development on this package be sponsored?
- IOS 16.4problem: Restricted network ports are not allowed HOT 3
- How to get post parameters ?
- How to set multiple responses for one endpoint?
- Question for loading index.html + subdirrectories HOT 1
- Support regular expression
- Bind operation not permitted - MacOS - UITests
- Privacy Manifest HOT 6
- HttpServer does not support for multicast
- Release new version from stable branch (Cocoapods)
- How to use the ssl
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from swifter.