有很多multipart/form-data文件上传解决方案,但我无法为Scala找到一个独立的.
Play2将此功能作为框架的一部分,Spray还支持多部分表单数据.不幸的是,这些似乎都完全集成到其他工具集中(我可能在这里错了).
我的服务器是使用Finagle(目前不支持多部分表单数据)开发的,如果可能的话,我想使用独立的lib或"自己动手"的解决方案.
这是典型的multipart/form-data消息:
--*****org.apache.cordova.formBoundary
Content-Disposition: form-data; name="value1"
First parameter content
--*****org.apache.cordova.formBoundary
Content-Disposition: form-data; name="value2"
Second parameter content
--*****org.apache.cordova.formBoundary
Content-Disposition: form-data; name="file"; filename="image.jpg"
Content-Type: image/jpeg
$%^&#$%^%#$
--*****org.apache.cordova.formBoundary--
Run Code Online (Sandbox Code Playgroud)
在此示例中,*****org.apache.cordova.formBoundary
是表单边界,因此分段上传包含2个文本参数和一个图像(为了清楚起见,我将图像数据连接起来).
如果一个比我更了解Scala的人可以给我一些关于如何解析这些内容的简要介绍,我将非常感激.
首先,我想我会快速拆分三个内容:
data.split("\\Q--*****org.apache.cordova.formBoundary\\E") foreach println
Run Code Online (Sandbox Code Playgroud)
但执行速度非常慢(更新 - 这是由于预热时间).是否有更有效的方法来拆分零件?我的策略是将内容分成几部分,然后将部分拆分成子部分.这是一个糟糕的方法吗?我见过用状态机解决类似的问题?什么是好的功能方法.请记住,我试图在尝试解决问题时学习一种适当的Scala方法.
更新:
我真的认为这个问题的解决方案是Scala中的一行或两行.如果有人通过光滑的解决方案绊倒这个问题,请花时间记下来.根据我的理解,可以使用模式匹配,解析组合器,提取或简单地拆分字符串来解析此消息.我正在努力寻找解决此类问题的最佳方法,因为我正在进行的项目涉及大量自然语言解析,我需要编写自己的自定义解析工具.我对Scala有了很好的理解,但没有什么比专家的建议好.
它不仅仅是解决问题,而是找到解决此类问题的最佳方法(并且希望最简单).
这可能是最糟糕的解决方案,并且无法以任何方式扩展,但为了快速从多部分请求中获取图像数据,我执行了以下操作(如果有人给出了更好的答案,我将取消标记我的答案):
// Take the request and split it into parts
var requestParts = request.content.toString(UTF_8).split("\\Q--*****org.apache.cordova.formBoundary\\E")
// Split the third part at the blank line
val imageParts = requestParts(3).split("\\n\\s*\\n")
// The part above the blank line is the header text
val imageHeader = imageParts(0)
// The part below the blank line is the image body
val imageBodyString = imageParts(1)
Run Code Online (Sandbox Code Playgroud)
稍后我会尝试改进这一点,但现在必须继续前进。另一天,另一个项目:-o