栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Play Framework 2.0中将文件上传为流

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Play Framework 2.0中将文件上传为流

我已经能够使用以下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),并且可以解决问题。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497719.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号