scala - File upload using Akka HTTP -
i trying implement file upload functionality in application using akka http. using akka-stream
version 2.4.4
.
here code (modified akka-doc)
path("fileupload") { post { extractrequestcontext { ctx => { implicit val materializer = ctx.materializer implicit val ec = ctx.executioncontext fileupload("fileupload") { case (metadata, bytesource) => val location = fileutil.getuploadpath(metadata) val updatedfilename = metadata.filename.replaceall(" ", "").replaceall("\"", "") val uniqfilename = uniquefileid.concat(updatedfilename) val fullpath = location + file.separator + uniqfilename val writer = new fileoutputstream(fullpath) val bufferedwriter = new bufferedoutputstream(writer) val result = bytesource.map(s => { bufferedwriter.write(s.toarray) }).runwith(sink.ignore) val result1 = bytesource.runwith(sink.foreach(s=>bufferedwriter.write(s.toarray))) await.result(result1, 5.seconds) bufferedwriter.flush() bufferedwriter.close() complete(uniqfilename) /*onsuccess(result) { x => bufferedwriter.flush() bufferedwriter.close() complete("hello world") }*/ } } } } }
this code working fine , uploading file given path. generating new file names appending uuid make sure file names unique. need return new file name caller. however, method not returning filename always. sometimes, finishing response has no content
.
can let me know doing wrong here?
there no need use standard blocking streams when have reactive streams purpose:
path("fileupload") { post { fileupload("fileupload") { case (fileinfo, filestream) => val sink = fileio.topath(paths.get("/tmp") 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 } } } } }
this code upload fileupload
multipart field file inside /tmp
directory. dumps content of input source respective file sink, returning message upon completion of write operation.
you may want tweak dispatcher used fileio
sources , sinks, described in their scaladocs.
Comments
Post a Comment