Search in sources :

Example 1 with FileUpload

use of io.vertx.ext.web.FileUpload in project vertx-examples by vert-x3.

the class Server method start.

@Override
public void start() throws Exception {
    Router router = Router.router(vertx);
    // Enable multipart form data parsing
    router.route().handler(BodyHandler.create().setUploadsDirectory("uploads"));
    router.route("/").handler(routingContext -> {
        routingContext.response().putHeader("content-type", "text/html").end("<form action=\"/form\" method=\"post\" enctype=\"multipart/form-data\">\n" + "    <div>\n" + "        <label for=\"name\">Select a file:</label>\n" + "        <input type=\"file\" name=\"file\" />\n" + "    </div>\n" + "    <div class=\"button\">\n" + "        <button type=\"submit\">Send</button>\n" + "    </div>" + "</form>");
    });
    // handle the form
    router.post("/form").handler(ctx -> {
        ctx.response().putHeader("Content-Type", "text/plain");
        ctx.response().setChunked(true);
        for (FileUpload f : ctx.fileUploads()) {
            System.out.println("f");
            ctx.response().write("Filename: " + f.fileName());
            ctx.response().write("\n");
            ctx.response().write("Size: " + f.size());
        }
        ctx.response().end();
    });
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
Also used : Router(io.vertx.ext.web.Router) FileUpload(io.vertx.ext.web.FileUpload)

Example 2 with FileUpload

use of io.vertx.ext.web.FileUpload in project incubator-servicecomb-java-chassis by apache.

the class VertxServerRequestToHttpServletRequest method getPart.

@Override
public Part getPart(String name) throws IOException, ServletException {
    Optional<FileUpload> upload = context.fileUploads().stream().filter(fileUpload -> fileUpload.name().equals(name)).findFirst();
    if (!upload.isPresent()) {
        LOGGER.error("No such file with name: {}.", name);
        return null;
    }
    final FileUpload fileUpload = upload.get();
    return new FileUploadPart(fileUpload);
}
Also used : BufferInputStream(org.apache.servicecomb.foundation.vertx.stream.BufferInputStream) HttpServerRequest(io.vertx.core.http.HttpServerRequest) Logger(org.slf4j.Logger) Enumeration(java.util.Enumeration) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) LoggerFactory(org.slf4j.LoggerFactory) MultiMap(io.vertx.core.MultiMap) Set(java.util.Set) IOException(java.io.IOException) HashMap(java.util.HashMap) RoutingContext(io.vertx.ext.web.RoutingContext) FileUpload(io.vertx.ext.web.FileUpload) AsyncContext(javax.servlet.AsyncContext) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Buffer(io.vertx.core.buffer.Buffer) Part(javax.servlet.http.Part) Map(java.util.Map) Optional(java.util.Optional) Cookie(javax.servlet.http.Cookie) Collections(java.util.Collections) SocketAddress(io.vertx.core.net.SocketAddress) FileUpload(io.vertx.ext.web.FileUpload)

Example 3 with FileUpload

use of io.vertx.ext.web.FileUpload in project parser-excel-elasticsearch by codingchili.

the class Website method setRouterAPI.

/**
 * Adds the upload route to the given router
 *
 * @param router the upload route is added to the given router
 */
private void setRouterAPI(Router router) {
    router.route("/api/upload").handler(context -> {
        Iterator<FileUpload> iterator = context.fileUploads().iterator();
        if (iterator.hasNext()) {
            MultiMap params = context.request().params();
            logger.info("Receiving uploaded file with request id " + params.get(UPLOAD_ID));
            FileUpload upload = context.fileUploads().iterator().next();
            vertx.fileSystem().readFile(upload.uploadedFileName(), file -> {
                parse(file.result(), params, upload.fileName(), Future.<Integer>future().setHandler(result -> {
                    if (result.succeeded()) {
                        String index = context.request().params().get(INDEX);
                        logger.info(String.format("Imported file '%s' successfully into '%s'.", upload.fileName(), index));
                        context.put(INDEX, index);
                        context.put(FILE, upload.fileName());
                        context.put(IMPORTED, result.result());
                        context.reroute(DONE);
                    } else {
                        context.put(MESSAGE, traceToText(result.cause()));
                        logger.log(Level.SEVERE, String.format("Failed to parse file '%s'.", upload.fileName()), result.cause());
                        context.reroute(ERROR);
                    }
                }));
            });
        } else {
            context.put(MESSAGE, NO_FILE_WAS_UPLOADED);
            context.reroute(ERROR);
        }
    });
}
Also used : VERSION(com.codingchili.ApplicationLauncher.VERSION) DeliveryOptions(io.vertx.core.eventbus.DeliveryOptions) MultiMap(io.vertx.core.MultiMap) Router(io.vertx.ext.web.Router) BodyHandler(io.vertx.ext.web.handler.BodyHandler) Context(io.vertx.core.Context) Level(java.util.logging.Level) Configuration(com.codingchili.Model.Configuration) ElasticWriter(com.codingchili.Model.ElasticWriter) JadeTemplateEngine(io.vertx.ext.web.templ.JadeTemplateEngine) JsonObject(io.vertx.core.json.JsonObject) PrintWriter(java.io.PrintWriter) Iterator(java.util.Iterator) StaticHandler(io.vertx.ext.web.handler.StaticHandler) StringWriter(java.io.StringWriter) FileParser(com.codingchili.Model.FileParser) Vertx(io.vertx.core.Vertx) ParserException(com.codingchili.Model.ParserException) Logger(java.util.logging.Logger) Future(io.vertx.core.Future) INDEXING_ELASTICSEARCH(com.codingchili.Model.Configuration.INDEXING_ELASTICSEARCH) FileUpload(io.vertx.ext.web.FileUpload) TemplateHandler(io.vertx.ext.web.handler.TemplateHandler) INDEX(com.codingchili.Model.FileParser.INDEX) Buffer(io.vertx.core.buffer.Buffer) AbstractVerticle(io.vertx.core.AbstractVerticle) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) MultiMap(io.vertx.core.MultiMap) FileUpload(io.vertx.ext.web.FileUpload)

Example 4 with FileUpload

use of io.vertx.ext.web.FileUpload in project vertx-web by vert-x3.

the class BodyHandlerTest method testFileUpload.

private void testFileUpload(String uploadsDir, int size) throws Exception {
    String name = "somename";
    String fileName = "somefile.dat";
    String contentType = "application/octet-stream";
    Buffer fileData = TestUtils.randomBuffer(size);
    router.route().handler(rc -> {
        Set<FileUpload> fileUploads = rc.fileUploads();
        assertNotNull(fileUploads);
        assertEquals(1, fileUploads.size());
        FileUpload upload = fileUploads.iterator().next();
        assertEquals(name, upload.name());
        assertEquals(fileName, upload.fileName());
        assertEquals(contentType, upload.contentType());
        assertEquals("binary", upload.contentTransferEncoding());
        assertEquals(fileData.length(), upload.size());
        String uploadedFileName = upload.uploadedFileName();
        assertTrue(uploadedFileName.startsWith(uploadsDir + File.separator));
        Buffer uploaded = vertx.fileSystem().readFileBlocking(uploadedFileName);
        assertEquals(fileData, uploaded);
        // the data is upload as HTML form, so the body should be empty
        Buffer rawBody = rc.getBody();
        assertEquals(0, rawBody.length());
        rc.response().end();
    });
    sendFileUploadRequest(fileData, 200, "OK");
}
Also used : Buffer(io.vertx.core.buffer.Buffer) FileUpload(io.vertx.ext.web.FileUpload)

Example 5 with FileUpload

use of io.vertx.ext.web.FileUpload in project java-chassis by ServiceComb.

the class VertxServerRequestToHttpServletRequest method getPart.

@Override
public Part getPart(String name) {
    Optional<FileUpload> upload = context.fileUploads().stream().filter(fileUpload -> fileUpload.name().equals(name)).findFirst();
    if (!upload.isPresent()) {
        LOGGER.debug("No such file with name: {}.", name);
        return null;
    }
    final FileUpload fileUpload = upload.get();
    return new FileUploadPart(fileUpload);
}
Also used : BufferInputStream(org.apache.servicecomb.foundation.vertx.stream.BufferInputStream) HttpServerRequest(io.vertx.core.http.HttpServerRequest) Logger(org.slf4j.Logger) Enumeration(java.util.Enumeration) Collection(java.util.Collection) ServletInputStream(javax.servlet.ServletInputStream) LoggerFactory(org.slf4j.LoggerFactory) MultiMap(io.vertx.core.MultiMap) Set(java.util.Set) HashMap(java.util.HashMap) RoutingContext(io.vertx.ext.web.RoutingContext) Collectors(java.util.stream.Collectors) FileUpload(io.vertx.ext.web.FileUpload) AsyncContext(javax.servlet.AsyncContext) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) HttpUtils(org.apache.servicecomb.foundation.common.http.HttpUtils) Buffer(io.vertx.core.buffer.Buffer) Part(javax.servlet.http.Part) Map(java.util.Map) Optional(java.util.Optional) Cookie(javax.servlet.http.Cookie) Collections(java.util.Collections) SocketAddress(io.vertx.core.net.SocketAddress) FileUpload(io.vertx.ext.web.FileUpload)

Aggregations

FileUpload (io.vertx.ext.web.FileUpload)6 Buffer (io.vertx.core.buffer.Buffer)5 MultiMap (io.vertx.core.MultiMap)3 HttpServerRequest (io.vertx.core.http.HttpServerRequest)2 SocketAddress (io.vertx.core.net.SocketAddress)2 Router (io.vertx.ext.web.Router)2 RoutingContext (io.vertx.ext.web.RoutingContext)2 Collections (java.util.Collections)2 Enumeration (java.util.Enumeration)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Optional (java.util.Optional)2 Set (java.util.Set)2 AsyncContext (javax.servlet.AsyncContext)2 ServletInputStream (javax.servlet.ServletInputStream)2 Cookie (javax.servlet.http.Cookie)2 Part (javax.servlet.http.Part)2 HttpHeaders (javax.ws.rs.core.HttpHeaders)2 BufferInputStream (org.apache.servicecomb.foundation.vertx.stream.BufferInputStream)2