मैं नीचे दिए गए कोड का उपयोग कर समाप्त हो गया। बहुत कठिन नहीं था, लेकिन वास्तव में इस बारे में कहीं स्प्रे नमूना उपलब्ध होना चाहिए था।
multipart/form-data
रूपों का उपयोग हमेशा किया जाना चाहिए (पारंपरिक application/x-www-form-urlencoded
के बजाय) यदि बाइनरी अपलोड शामिल हैं। अधिक जानकारी here।
मेरे आवश्यकताएं थीं: यथोचित बड़े आकार की बाइनरी फ़ाइलों को अपलोड करने
- जरूरत
- क्षेत्रों (या URL में नहीं एम्बेडेड अपलोड के फ़ाइल नाम)
कुछ सवाल के रूप में मेटाडाटा करना चाहते थे :
- जिस तरह से मैं "सर्वोत्तम" तरीके से त्रुटियों का प्रबंधन कर रहा हूं?
यह क्लाइंट के साथ "मानव" (डीबगिंग में, हम हैं) के रूप में व्यवहार करने के लिए आरईएसटी एपीआई डिज़ाइन के सार में है, संदेश के साथ कुछ गलत होने पर सार्थक त्रुटि संदेश दे रहा है।
post {
// Note: We cannot use a regular 'return' to provide a routing mid-way. The last item matters, but we can
// have a 'var' which collects the correct success/error info into it. It's a write-once variable.
//
var ret: Option[Route] = None
// Multipart form
//
// To exercise this:
// $ curl -i -F "[email protected]" -F "computer=MYPC" http://localhost:8080/your/route; echo
//
entity(as[MultipartFormData]) { formData =>
val file = formData.get("file")
// e.g. Some(
// BodyPart(HttpEntity(application/octet-stream, ...binary data...,
// List(Content-Type: application/octet-stream, Content-Disposition: form-data; name=file; filename=<string>)))
log.debug(s".file: $file")
val computer = formData.get("computer")
// e.g. Some(BodyPart(HttpEntity(text/plain; charset=UTF-8,MYPC), List(Content-Disposition: form-data; name=computer)))
log.debug(s"computer: $computer")
// Note: The types are mentioned below simply to make code comprehension easier. Scala could deduce them.
//
for(file_bodypart: BodyPart <- file;
computer_bodypart: BodyPart <- computer) {
// BodyPart: http://spray.io/documentation/1.1-SNAPSHOT/api/index.html#spray.http.BodyPart
val file_entity: HttpEntity = file_bodypart.entity
//
// HttpEntity: http://spray.io/documentation/1.1-SNAPSHOT/api/index.html#spray.http.HttpEntity
//
// HttpData: http://spray.io/documentation/1.1-SNAPSHOT/api/index.html#spray.http.HttpData
log.debug(s"File entity length: ${file_entity.data.length}")
val file_bin= file_entity.data.toByteArray
log.debug(s"File bin length: ${file_bin.length}")
val computer_name = computer_bodypart.entity.asString //note: could give encoding as parameter
log.debug(s"Computer name: $computer_name")
// We have the data here, pass it on to an actor and return OK
//
...left out, application specific...
ret = Some(complete("Got the file, thanks.")) // the string doesn't actually matter, we're just being polite
}
ret.getOrElse(
complete(BadRequest, "Missing fields, expecting file=<binary>, computer=<string>")
)
}
}
मैं भी हैरान था क्यों में इस के लिए एक उल्लेख नहीं है मैनुअल, कोई नमूने, और इतने पर .. तो हम में से कम से कम दो हैं। वास्तव में स्प्रे के लिए कुछ सहायक होने की उम्मीद होगी। – akauppi