Search in sources :

Example 1 with ContentDisposition

use of cn.taketoday.http.ContentDisposition in project today-framework by TAKETODAY.

the class MultipartIterator method obtainNext.

/**
 * @throws NotMultipartRequestException if this request is not of type multipart/form-data
 * @throws MultipartException multipart parse failed
 */
public RequestPart obtainNext(LightHttpConfig config, MultipartConfiguration multipartConfig) throws IOException {
    hasNext = false;
    // 先解析 header
    // Content-Disposition
    final String contentDispositionString = Utils.readLine(inputStream);
    // Content-Type
    final String contentType = Utils.readLine(inputStream);
    // final HttpHeaders httpHeaders = Utils.readHeaders(inputStream, config);
    final MultipartInputStream inputStream = this.inputStream;
    final int partSize = inputStream.tail - inputStream.head;
    final DataSize maxFileSize = multipartConfig.getMaxFileSize();
    if (partSize > maxFileSize.toBytes()) {
        throw new FileSizeExceededException(maxFileSize, null).setActual(DataSize.ofBytes(partSize));
    }
    final ContentDisposition contentDisposition = ContentDisposition.parse(contentDispositionString);
    // if (httpHeaders.containsKey(Constant.CONTENT_TYPE)) {
    if (StringUtils.isNotEmpty(contentType)) {
        if (partSize > config.getMaxMultipartInMemSize()) {
            final String tempLocation = multipartConfig.getLocation();
            final File tempFileDir = new File(tempLocation);
            final String randomString = StringUtils.generateRandomString(10);
            final File tempFile = new File(tempFileDir, randomString);
            // save to temp file
            try (final FileOutputStream fileOutput = new FileOutputStream(tempFile)) {
                final int bufferSize = config.getMultipartBufferSize();
                // readTimes > 1
                final int readTimes = partSize / bufferSize;
                if (readTimes == 0) {
                    // part size 太小了 直接一次性读完
                    byte[] buffer = Utils.readBytes(inputStream, partSize);
                    fileOutput.write(buffer, 0, partSize);
                    final LightMultipartFile multipartFile = new LightMultipartFile(tempFile, contentDisposition, contentType, partSize);
                    multipartFile.setCachedBytes(buffer);
                    return multipartFile;
                } else {
                    // 分次读取
                    byte[] buffer = new byte[bufferSize];
                    int bytesRead = 0;
                    for (int i = 0; i < readTimes; i++) {
                        bytesRead += inputStream.read(buffer, 0, bufferSize);
                        fileOutput.write(buffer, 0, bytesRead);
                    }
                    // 读取剩余字节
                    buffer = Utils.readBytes(inputStream, partSize - bytesRead);
                    fileOutput.write(buffer);
                    return new LightMultipartFile(tempFile, contentDisposition, contentType, partSize);
                }
            }
        } else {
            final byte[] bytes = Utils.readBytes(inputStream, partSize);
            // inputStream memory
            return new LightMultipartFile(bytes, contentDisposition, contentType, partSize);
        }
    } else {
        final String name = contentDisposition.getName();
        final byte[] bytes = Utils.readBytes(inputStream, partSize);
        return new FieldRequestPart(bytes, name);
    }
}
Also used : ContentDisposition(cn.taketoday.http.ContentDisposition) DataSize(cn.taketoday.util.DataSize) FileOutputStream(java.io.FileOutputStream) FileSizeExceededException(cn.taketoday.http.FileSizeExceededException) File(java.io.File)

Example 2 with ContentDisposition

use of cn.taketoday.http.ContentDisposition in project today-framework by TAKETODAY.

the class ServletMultipartRequest method parseRequest.

private MultiValueMap<String, MultipartFile> parseRequest(HttpServletRequest request) {
    try {
        Collection<Part> parts = request.getParts();
        LinkedMultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<>(parts.size());
        for (Part part : parts) {
            String headerValue = part.getHeader(HttpHeaders.CONTENT_DISPOSITION);
            ContentDisposition disposition = ContentDisposition.parse(headerValue);
            String filename = disposition.getFilename();
            files.add(part.getName(), new ServletPartMultipartFile(part, filename));
        }
        return files;
    } catch (IOException e) {
        throw new MultipartException("MultipartFile parsing failed.", e);
    } catch (ServletException e) {
        throw new NotMultipartRequestException("This is not a multipart request", e);
    } catch (Throwable ex) {
        String msg = ex.getMessage();
        if (msg != null && msg.contains("size") && msg.contains("exceed")) {
            throw new MaxUploadSizeExceededException(-1, ex);
        }
        throw new MultipartException("Failed to parse multipart servlet request", ex);
    }
}
Also used : LinkedMultiValueMap(cn.taketoday.core.LinkedMultiValueMap) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) NotMultipartRequestException(cn.taketoday.web.bind.NotMultipartRequestException) MultipartFile(cn.taketoday.web.multipart.MultipartFile) MaxUploadSizeExceededException(cn.taketoday.web.multipart.MaxUploadSizeExceededException) ContentDisposition(cn.taketoday.http.ContentDisposition) Part(jakarta.servlet.http.Part) MultipartException(cn.taketoday.web.bind.MultipartException)

Example 3 with ContentDisposition

use of cn.taketoday.http.ContentDisposition in project today-framework by TAKETODAY.

the class ResourceHttpMessageReaderTests method readResourceAsMono.

@Test
void readResourceAsMono() throws IOException {
    String filename = "test.txt";
    String body = "Test resource content";
    ContentDisposition contentDisposition = ContentDisposition.attachment().name("file").filename(filename).build();
    MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
    response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
    response.getHeaders().setContentDisposition(contentDisposition);
    response.setBody(Mono.just(stringBuffer(body)));
    Resource resource = reader.readMono(ResolvableType.fromClass(ByteArrayResource.class), response, Collections.emptyMap()).block();
    assertThat(resource).isNotNull();
    assertThat(resource.getName()).isEqualTo(filename);
    assertThat(resource.getInputStream()).hasContent(body);
}
Also used : ContentDisposition(cn.taketoday.http.ContentDisposition) Resource(cn.taketoday.core.io.Resource) ByteArrayResource(cn.taketoday.core.io.ByteArrayResource) MockClientHttpResponse(cn.taketoday.http.client.reactive.MockClientHttpResponse) Test(org.junit.jupiter.api.Test)

Example 4 with ContentDisposition

use of cn.taketoday.http.ContentDisposition in project today-infrastructure by TAKETODAY.

the class ServletMultipartRequest method parseRequest.

private MultiValueMap<String, MultipartFile> parseRequest(HttpServletRequest request) {
    try {
        Collection<Part> parts = request.getParts();
        LinkedMultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<>(parts.size());
        for (Part part : parts) {
            String headerValue = part.getHeader(HttpHeaders.CONTENT_DISPOSITION);
            ContentDisposition disposition = ContentDisposition.parse(headerValue);
            String filename = disposition.getFilename();
            if (filename != null) {
                if (filename.startsWith("=?") && filename.endsWith("?=")) {
                    filename = MimeDelegate.decode(filename);
                }
                files.add(part.getName(), new ServletPartMultipartFile(part, filename));
            }
        }
        return files;
    } catch (IOException e) {
        throw new MultipartException("MultipartFile parsing failed.", e);
    } catch (ServletException e) {
        throw new NotMultipartRequestException("This is not a multipart request", e);
    } catch (Throwable ex) {
        String msg = ex.getMessage();
        if (msg != null && msg.contains("size") && msg.contains("exceed")) {
            throw new MaxUploadSizeExceededException(-1, ex);
        }
        throw new MultipartException("Failed to parse multipart servlet request", ex);
    }
}
Also used : LinkedMultiValueMap(cn.taketoday.core.LinkedMultiValueMap) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) NotMultipartRequestException(cn.taketoday.web.bind.NotMultipartRequestException) ServletPartMultipartFile(cn.taketoday.web.multipart.ServletPartMultipartFile) MultipartFile(cn.taketoday.web.multipart.MultipartFile) MaxUploadSizeExceededException(cn.taketoday.web.multipart.MaxUploadSizeExceededException) ServletPartMultipartFile(cn.taketoday.web.multipart.ServletPartMultipartFile) ContentDisposition(cn.taketoday.http.ContentDisposition) Part(jakarta.servlet.http.Part) MultipartException(cn.taketoday.web.bind.MultipartException)

Example 5 with ContentDisposition

use of cn.taketoday.http.ContentDisposition in project today-infrastructure by TAKETODAY.

the class ResourceHttpMessageReaderTests method readResourceAsMono.

@Test
void readResourceAsMono() throws IOException {
    String filename = "test.txt";
    String body = "Test resource content";
    ContentDisposition contentDisposition = ContentDisposition.attachment().name("file").filename(filename).build();
    MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
    response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
    response.getHeaders().setContentDisposition(contentDisposition);
    response.setBody(Mono.just(stringBuffer(body)));
    Resource resource = reader.readMono(ResolvableType.fromClass(ByteArrayResource.class), response, Collections.emptyMap()).block();
    assertThat(resource).isNotNull();
    assertThat(resource.getName()).isEqualTo(filename);
    assertThat(resource.getInputStream()).hasContent(body);
}
Also used : ContentDisposition(cn.taketoday.http.ContentDisposition) Resource(cn.taketoday.core.io.Resource) ByteArrayResource(cn.taketoday.core.io.ByteArrayResource) MockClientHttpResponse(cn.taketoday.http.client.reactive.MockClientHttpResponse) Test(org.junit.jupiter.api.Test)

Aggregations

ContentDisposition (cn.taketoday.http.ContentDisposition)5 LinkedMultiValueMap (cn.taketoday.core.LinkedMultiValueMap)2 ByteArrayResource (cn.taketoday.core.io.ByteArrayResource)2 Resource (cn.taketoday.core.io.Resource)2 MockClientHttpResponse (cn.taketoday.http.client.reactive.MockClientHttpResponse)2 MultipartException (cn.taketoday.web.bind.MultipartException)2 NotMultipartRequestException (cn.taketoday.web.bind.NotMultipartRequestException)2 MaxUploadSizeExceededException (cn.taketoday.web.multipart.MaxUploadSizeExceededException)2 MultipartFile (cn.taketoday.web.multipart.MultipartFile)2 ServletException (jakarta.servlet.ServletException)2 Part (jakarta.servlet.http.Part)2 IOException (java.io.IOException)2 Test (org.junit.jupiter.api.Test)2 FileSizeExceededException (cn.taketoday.http.FileSizeExceededException)1 DataSize (cn.taketoday.util.DataSize)1 ServletPartMultipartFile (cn.taketoday.web.multipart.ServletPartMultipartFile)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1