我已经能够使用以下Scala控制器代码将数据流式传输到第三方API:
def uploadFile() = Action( parse.multipartFormData(myPartHandler) ) { request => Ok("Done") }def myPartHandler: BodyParsers.parse.Multipart.PartHandler[MultipartFormData.FilePart[Result]] = { parse.Multipart.handleFilePart { case parse.Multipart.FileInfo(partName, filename, contentType) => //Still dirty: the path of the file is in the partName... String path = partName; //Set up the PipedOutputStream here, give the input stream to a worker thread val pos:PipedOutputStream = new PipedOutputStream(); val pis:PipedInputStream = new PipedInputStream(pos); val worker:UploadFileWorker = new UploadFileWorker(path,pis); worker.contentType = contentType.get; worker.start(); //Read content to the POS Iteratee.fold[Array[Byte], PipedOutputStream](pos) { (os, data) => os.write(data) os }.mapDone { os => os.close() Ok("upload done") } } }UploadFileWorker是一个非常简单的Java类,其中包含对第三方API的调用。
public class UploadFileWorker extends Thread {String path;PipedInputStream pis;public String contentType = "";public UploadFileWorker(String path, PipedInputStream pis) { super(); this.path = path; this.pis = pis;}public void run() { try { myApi.store(pis, path, contentType); pis.close(); } catch (Exception ex) { ex.printStackTrace(); try {pis.close();} catch (Exception ex2) {} }}}
它不是完全完美的,因为我希望将路径恢复为Action的参数,但我无法做到这一点。因此,我添加了一段javascript,它更新了输入字段的名称(并因此更新了partName),并且可以解决问题。



