perwendel / spark

A simple expressive web framework for java. Spark has a kotlin DSL https://github.com/perwendel/spark-kotlin
Apache License 2.0
9.63k stars 1.56k forks source link

Spark Java - strange behavior when uploading files #1265

Open sleepdan opened 1 year ago

sleepdan commented 1 year ago

In my project I want to try to upload files, here is the part of the code responsible for this:

        MultipartConfigElement multipartConfigElement =
                new MultipartConfigElement(
                        "/tmp_files",
                        avatarSize,
                        avatarSize,
                        1024
                );

        request.raw().setAttribute(
                "org.eclipse.jetty.multipartConfig",
                multipartConfigElement
        );

        Part uploadedFile = request.raw().getPart("file");

And a request to upload a file using Idea's http client:

POST http://localhost:8080/users/me/avatar
Content-Type: multipart/form-data; boundary=abcd
Authorization: Bearer {{authToken}}

--abcd
Content-Disposition: form-data; name="file"; filename="test.png"

< /Users/user1/resources/test.png
--abcd--

where test.png is a regular picture. But when I try to load in this code place:

Part uploadedFile = request.raw().getPart("file");

I get an error:

java.nio.file.NoSuchFileException: /tmp_files/MultiPart11851484240893602177
    at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:106)
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
    at java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:218)
    at java.base/java.nio.file.Files.newByteChannel(Files.java:375)
    at java.base/java.nio.file.Files.createFile(Files.java:652)

It can be assumed that this error is due to the fact that there are no write permissions to the root of the file system (I'm testing on mac os, under the user). But if i try to upload another file - which is just a zip file then everything works.

POST http://{{host}}/users/me/avatar
Content-Type: multipart/form-data; boundary=abcd
Authorization: Bearer {{authToken}}

--abcd
Content-Disposition: form-data; name="file"; filename="file123.zip"

< /Users/18493151/develop/icandev/api-gateway/src/main/resources/file123.zip
--abcd--

and no exception in this line:

Part uploadedFile = request.raw().getPart("file");

Why is this happening? Why does the result depend on the file type?

sparkjava version 2.9.4

ChaneWq commented 1 year ago

I don't know.