Search in sources :

Example 6 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();
        assertNull(rawBody);
        rc.response().end();
    });
    sendFileUploadRequest(fileData, 200, "OK");
}
Also used : Buffer(io.vertx.core.buffer.Buffer) FileUpload(io.vertx.ext.web.FileUpload)

Example 7 with FileUpload

use of io.vertx.ext.web.FileUpload in project vertx-zero by silentbalanceyh.

the class FileResolver method resolve.

@Override
public Epsilon<T> resolve(final RoutingContext context, final Epsilon<T> income) {
    final Set<FileUpload> fileUploads = context.fileUploads();
    if (Values.ONE == fileUploads.size()) {
        final FileUpload fileUpload = fileUploads.iterator().next();
        // Returned directly reference for FileUpload
        if (income.getArgType().isAssignableFrom(FileUpload.class)) {
            income.setValue((T) fileUpload);
        } else if (income.getArgType() == File.class) {
            // File object construction
            final Object ret = ZeroSerializer.getValue(income.getArgType(), fileUpload.uploadedFileName());
            income.setValue((T) ret);
        } else if (income.getArgType().isArray()) {
            // byte[]
            if (byte.class == income.getArgType().getComponentType() || Byte.class == income.getArgType().getComponentType()) {
                final FileSystem fileSystem = context.vertx().fileSystem();
                final Buffer buffer = fileSystem.readFileBlocking(fileUpload.uploadedFileName());
                income.setValue((T) buffer.getBytes());
            }
        } else if (Buffer.class.isAssignableFrom(income.getArgType())) {
            // Buffer
            final FileSystem fileSystem = context.vertx().fileSystem();
            final Buffer buffer = fileSystem.readFileBlocking(fileUpload.uploadedFileName());
            income.setValue((T) buffer);
        }
    } else {
        // Multi Files only support Set<FileUpload>
        income.setValue((T) fileUploads);
    }
    return income;
}
Also used : Buffer(io.vertx.core.buffer.Buffer) FileSystem(io.vertx.core.file.FileSystem) File(java.io.File) FileUpload(io.vertx.ext.web.FileUpload)

Example 8 with FileUpload

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

the class GraphQLHandlerImpl method parseMultipartAttributes.

private GraphQLInput parseMultipartAttributes(RoutingContext rc) {
    MultiMap attrs = rc.request().formAttributes();
    @SuppressWarnings("unchecked") Map<String, Object> filesMap = (Map<String, Object>) Json.decodeValue(attrs.get("map"), Map.class);
    GraphQLInput graphQLInput = GraphQLInput.decode(Json.decodeValue(attrs.get("operations")));
    Map<String, Map<String, Object>> variablesMap = new HashMap<>();
    Iterable<GraphQLQuery> batch = (graphQLInput instanceof GraphQLBatch) ? (GraphQLBatch) graphQLInput : Collections.singletonList((GraphQLQuery) graphQLInput);
    int i = 0;
    Iterator<GraphQLQuery> iterator = batch.iterator();
    for (; iterator.hasNext(); i++) {
        GraphQLQuery query = iterator.next();
        Map<String, Object> variables = new HashMap<>();
        variables.put("variables", query.getVariables());
        variablesMap.put(String.valueOf(i), variables);
    }
    for (Map.Entry<String, Object> entry : filesMap.entrySet()) {
        for (Object fullPath : (List) entry.getValue()) {
            String[] path = ((String) fullPath).split("\\.");
            int end = path.length;
            int idx = -1;
            if (IS_NUMBER.matcher(path[end - 1]).matches()) {
                idx = Integer.parseInt(path[end - 1]);
                --end;
            }
            Map<?, ?> variables;
            int start = 0;
            if (IS_NUMBER.matcher(path[0]).matches()) {
                variables = variablesMap.get(path[0]);
                ++start;
            } else {
                variables = variablesMap.get("0");
            }
            String attr = path[--end];
            Map obj = variables;
            for (; start < end; ++start) {
                String token = path[start];
                obj = (Map) obj.get(token);
            }
            FileUpload file = rc.fileUploads().stream().filter(f -> f.name().equals(entry.getKey())).findFirst().orElse(null);
            if (file != null) {
                if (idx == -1) {
                    obj.put(attr, file);
                } else {
                    ((List) obj.get(attr)).set(idx, file);
                }
            }
        }
    }
    return graphQLInput;
}
Also used : JsonObject(io.vertx.core.json.JsonObject) Collectors.toList(java.util.stream.Collectors.toList) FileUpload(io.vertx.ext.web.FileUpload)

Example 9 with FileUpload

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

the class BodyHandlerTest method testFileUploadSize.

@Test
public void testFileUploadSize() throws Exception {
    String uploadsDirectory = tempUploads.newFolder().getPath();
    router.clear();
    router.route().handler(BodyHandler.create().setDeleteUploadedFilesOnEnd(true).setUploadsDirectory(uploadsDirectory));
    int realSize = 20000;
    router.route().handler(ctx -> {
        String specData = ctx.request().formAttributes().get("specData");
        System.out.println(specData);
        FileUpload file = ctx.fileUploads().iterator().next();
        long uploadSize = file.size();
        assertEquals(realSize, uploadSize);
        ctx.end();
    });
    String name = "file";
    String fileName = "/C:/Users/vishal.b05/Desktop/1p.png";
    String contentType = "application/octet-stream";
    testRequest(HttpMethod.POST, "/", req -> {
        String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
        Buffer buffer = Buffer.buffer();
        String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: " + contentType + "\r\n" + // "Content-Transfer-Encoding: binary\r\n" +
        "\r\n";
        buffer.appendString(header);
        buffer.appendBuffer(TestUtils.randomBuffer(realSize));
        String footer = "\r\n--" + boundary + "\r\n";
        buffer.appendString(footer);
        String extra = "Content-Disposition: form-data; name=\"specData\"\r\n\r\n{\"id\":\"abc@xyz.com\"}\r\n" + "--" + boundary + "--\r\n\r\n";
        buffer.appendString(extra);
        req.headers().set("content-length", String.valueOf(buffer.length()));
        req.headers().set("content-type", "multipart/form-data; boundary=" + boundary);
        req.setChunked(true);
        req.write(buffer);
    }, 200, "OK", null);
    assertWaitUntil(() -> vertx.fileSystem().readDirBlocking(uploadsDirectory).isEmpty());
}
Also used : Buffer(io.vertx.core.buffer.Buffer) FileUpload(io.vertx.ext.web.FileUpload) Test(org.junit.Test)

Aggregations

FileUpload (io.vertx.ext.web.FileUpload)9 Buffer (io.vertx.core.buffer.Buffer)7 MultiMap (io.vertx.core.MultiMap)3 HttpServerRequest (io.vertx.core.http.HttpServerRequest)2 JsonObject (io.vertx.core.json.JsonObject)2 SocketAddress (io.vertx.core.net.SocketAddress)2 Router (io.vertx.ext.web.Router)2 RoutingContext (io.vertx.ext.web.RoutingContext)2 Collection (java.util.Collection)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 Collectors (java.util.stream.Collectors)2 AsyncContext (javax.servlet.AsyncContext)2 ServletInputStream (javax.servlet.ServletInputStream)2 Cookie (javax.servlet.http.Cookie)2