我正在服务器端使用Akka HTTP上传excel表并保存到本地
def uploadFile(fileData: Multipart.FormData) = {
println(" uploadFile ")
// path("user" / "upload" / "file") {
/* (post & entity(as[Multipart.FormData])) { fileData =>*/
complete {
val fileName = UUID.randomUUID().toString
val temp = System.getProperty("java.io.tmpdir")
val filePath = temp + "/" + fileName+".xls"
// var filePath = current.configuration.getString("upload.file.path").get + "/" + fileName
println(fileData.getParts() + " - " + fileData.getMediaType() + " filePath " + filePath + " fileName " + fileName)
val processingFileUpload = processFile(filePath, fileData)
/*val poResult = Await.result(processingFileUpload, 50 seconds)
println(" processFile " + poResult)*/
processingFileUpload.map { fileSize =>
HttpResponse(StatusCodes.OK, entity = s"File successfully uploaded. Fil size is $fileSize")
}.recover {
case ex: Exception => HttpResponse(StatusCodes.InternalServerError, entity = "Error in file uploading")
}
// }
// }
}
}
我的processFile是
private def processFile(filePath: String, fileData: Multipart.FormData) = {
val fileOutput = new FileOutputStream(filePath)
println(" fileOutput " + fileOutput+" fileDatas "+fileData.parts.module)
// fileData.parts.mapAsync(1) { bodyPart =>
fileData.parts.mapAsyncUnordered(1) { bodyPart =>
println(" bodyPartLog " + bodyPart)
def writeFileOnLocal(array: Array[Byte], byteString: ByteString): Array[Byte] = {
println(" arraysdss " + array)
val byteArray: Array[Byte] = byteString.toArray
fileOutput.write(byteArray)
println(" sdssasx " + byteArray)
array ++ byteArray
}
bodyPart.entity.dataBytes.runFold(Array[Byte]())(writeFileOnLocal)
}.runFold(0)(_ + _.length)
}
我已经捕获了mapAsync和mapAsyncUnordered我每次都得到错误的文件上传它直接跳转到异常如何通过上传服务将数据写入我的本地服务器
答案 0 :(得分:0)
我已经使用了另一种方法进行文件上传,它也正常工作
(post & entity(as[Multipart.FormData])) { request =>
extractRequestContext {
ctx => {
implicit val materializer = ctx.materializer
implicit val ec = ctx.executionContext
fileUpload("fileUpload") {
case (fileInfo, fileStream) =>
val localPath = "c:\\test"
val sink = FileIO.toPath(Paths.get(localPath) resolve fileInfo.fileName)
val writeResult = fileStream.runWith(sink)
onSuccess(writeResult) { result =>
result.status match {
case Success(_) => complete(s"Successfully written ${result.count} bytes")
case Failure(e) => throw e
}
}
}
}
}
}