Convert File to FileItem Using Scala

474 Views Asked by At

I have a web UI that accepts a file uploaded as scalatra.servlet.FileItem and is passed to several functions that do something with the file uploaded. This is working properly. Now, I need to make a junit test for this feature. With this junit test, the file no longer needs to be uploaded. I only have to read it from a location.

val inFile = new File("resources/sample.xml")

My problem is that i need to pass this to the function that accepts FileItem as parameter. I get a Type mismatch error. How do i change this to FileItem? I have looked at several articles but none worked. I'm wondering if it is even possible to convert from File to FileItem. I have also tried using

val fileItem = new DiskFileItem("payloadFile", "plain/text", false, "Payload_FileItem", availableBytes, inFile).asInstanceOf[org.scalatra.servlet.FileItem]

but this still had error:

java.lang.ClassCastException: org.apache.commons.fileupload.disk.DiskFileItem cannot be cast to org.scalatra.servlet.FileItem

I also tried using inputStreams but don't know what to do next to convert from the stream to FileItem (or if it is even possible).

val inputStream = getSystemClassLoader.getResourceAsStream("resources/sample.xml")

Hope anyone can help. Thanks.

1

There are 1 best solutions below

0
On

I think there is a lot of confusion here; as there are actually two classes around - the apache ones, but then that scala framework has its own version of things.

See here - FileUploadSupport.scala defines its own class

case class FileItem(part: Part) {

So it looks like you actually could create instances of that class directly - if you manage to figure what that part parameter is about.

My idea to get to an answer - figure the full name of that Part parameter; and then see if you can use that knowledge to directly instantiate such an instance of org.scalatra.servlet.FileItem from there.