Skip to content

Instantly share code, notes, and snippets.

@tbje
Created December 2, 2010 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbje/725200 to your computer and use it in GitHub Desktop.
Save tbje/725200 to your computer and use it in GitHub Desktop.
http x((:/ ("www.mysite.com") / "upload") <<
("file", new java.io.File("""path\to\file\""")) as_str)
}
http x((:/ ("www.mysite.com") / "upload") <<
("file", "myFilename", () => inputStream) as_str)
}
import dispatch._
import dispatch.Http._
import dispatch.mime.Mime._
class FileBodyFromStream(
filename: String,
inputStream: () => java.io.InputStream,
lengthOpt: Option[Long] = None
) extends org.apache.http.entity.mime.content.FileBody(new java.io.File("")) {
val (writeToFunc, length) = lengthOpt.map(length=>
((out: java.io.OutputStream) => Stream.continually(inputStream().read).
takeWhile(_ != -1).foreach(out.write(_)),
length
)
) getOrElse { // No length supplied, read stream to get length
val buffer = new java.io.ByteArrayOutputStream()
Stream.continually(inputStream().read).takeWhile(_ != -1).foreach(buffer.write(_))
((out: java.io.OutputStream) => buffer.writeTo(out),
buffer.size().toLong
)
}
override def writeTo(out: java.io.OutputStream) = writeToFunc(out)
override def getContentLength() = length
override def getFilename() = filename
}
class SuperMimeRequest(r: Request) extends MimeRequest(r) {
def <<* (
name: String,
filename: String,
inputStream: ()=>java.io.InputStream,
length: Option[Long] = None
) = r next add(name, new FileBodyFromStream(filename, inputStream, length))
}
object SyncApp extends Application {
implicit def Request2SuperMimeRequest(r: Request) = new SuperMimeRequest(r)
val (filename, inputStream, contentLength) = ...
http x((:/ ("www.mysite.com") / "upload") <<*
("file", filename, () => inputStream, Some(contentLength)) as_str)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment