swagger-core icon indicating copy to clipboard operation
swagger-core copied to clipboard

FileUpload not working with Jersey/Java

Open gaffa opened this issue 13 years ago • 13 comments

I have the following service-method:

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation("submit")
    public Response uploadTranslation(
            @ApiParam(required = false) @FormDataParam("comment") String comment,
            @ApiParam @FormDataParam("translation") Translation translation,
            @ApiParam @FormDataParam("sourceDocument") InputStream sourceDocument,
            @ApiParam @FormDataParam("additionalContent") InputStream additionalContent) {
        return null;
    }

it results in swagger-ui not rendering the file-inputs as file-chooser but text-fields. Same counts for spring. I spent all day trying and trying and I really think its a bug. Unfortunately I dont know the least of scala. Anyone has any idea why this would not work?

toni tam has posted this code on the mailing-list and it was confirmed working:

  @POST
  @Path("/uploadImage")
  @Consumes(Array(MediaType.MULTIPART_FORM_DATA))
  @ApiOperation(value = "uploads an image")
  def uploadFile(
    @ApiParam(value = "String to pass during submit") @FormDataParam("test") testString: String,
    @ApiParam(value = "file to upload") @FormDataParam("file") inputStream: InputStream,
    @ApiParam(value = "file detail") @FormDataParam("file") fileDetail: FormDataContentDisposition) = {
    println("testString: " + testString)
    val uploadedFileLocation = "./" + fileDetail.getFileName
    IOUtils.copy(inputStream, new FileOutputStream(uploadedFileLocation))
    val msg = "File uploaded to " + uploadedFileLocation + ", " + (new java.io.File(uploadedFileLocation)).length + " bytes"
    val output = new com.wordnik.swagger.sample.model.ApiResponse(200, msg)
    Response.status(200).entity(output).build()
  }

I of course have the latest versions of both ui- and jersey-code. When I do something like this:


@ApiParamsImplicit(@ApiParamImplicit(dataType = "file", name = "file", paramType = "body"))

I get a file chooser but I dont know where to go from there. I also need a solution which will still keep the api clean and easily usable by coded clients...

Thinkink of this point.. is it really necessary to bind the service to translation.json instead of just translation?

gaffa avatar May 09 '13 16:05 gaffa

Hi, are you using jax-rs or play2?

fehguy avatar May 09 '13 16:05 fehguy

jax-rs it is. the rest of our application is spring but spring-swagger has no support for files at all... i can provide you with the complete example project if it helps...

gaffa avatar May 09 '13 17:05 gaffa

https://www.dropbox.com/s/zkt41oc7bg7yqqo/swagger-jaxrs.zip

gaffa avatar May 09 '13 17:05 gaffa

Hi, just got this, looking

fehguy avatar May 09 '13 18:05 fehguy

Hi, three things to do (all easy).

  1. Your web.xml is not referring to the jersey version of swagger. Change the scanning package to this:
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>foo; com.wordnik.swagger.jersey.listing</param-value>
        </init-param>

note jersey instead of jaxrs. That was the biggest issue.

  1. Your additionalContent should not be of type InputStream, it should be FormDataContentDisposition:
@ApiParam @FormDataParam("additionalContent") FormDataContentDisposition additionalContent)
  1. You should configure the json mapper to not write nulls (this would bite you later). Create a mapper like this:
package foo;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;


@Provider
@Produces(MediaType.APPLICATION_JSON)
public class Mapper extends JacksonJaxbJsonProvider {
    private static ObjectMapper commonMapper = null;

    public Mapper() {
        if(commonMapper == null){
            ObjectMapper mapper = new ObjectMapper();

            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            commonMapper = mapper;
        }
        super.setMapper(commonMapper);
    }   
}

give that a whirl and post back!

fehguy avatar May 09 '13 20:05 fehguy

Wow. Thanks a lot! So it was not a bug but me. Thank you for your time! I have another problem now. Its the Translation-object. swagger-ui will not insert the model when I click "click to set as parameter value" and when I enter the value myself I will get

HTTP Status 500 - com.sun.jersey.server.impl.model.parameter.multivalued.ExtractorContainerException: Error unmarshalling JAXB object of type &quot;class foo.Translation&quot;

...

javax.xml.bind.UnmarshalException
             - with linked exception:
            [org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content ist nicht zulässig in Prolog.]

("Content not allowed in prolog.").

As you were already so nice and had a look at my code: would you mind having a look at that?

My Service at the moment looks like this:

``` java`

@POST
@Path("/test")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("test")
public Response test(
        @ApiParam(required = true) @FormDataParam("translation") Translation translation){
    return null;
}

@POST
@Path("/translation")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("submit")
public Response uploadTranslation(
        @FormDataParam("comment") String comment,
        //@ApiParam(required = true) @FormDataParam("translation") Translation translation,
        @FormDataParam("sourceDocument") InputStream sourceDocument,
        @FormDataParam("sourceDocument") FormDataContentDisposition sourceDocumentData,
        @FormDataParam("additionalContent") InputStream additionalContent,
        @FormDataParam("additionalContent") FormDataContentDisposition additionalContentData) {
    return null;
}

As it is I can use the method submit (without translation object). By the way: I was so happy when I ran into the breakpoint :). But not the other method. 
I am not sure if you noticed but swagger-ui is included in my project and mapped under /. I modified the index to directly navigate to the service. So if you start the webapp on 8080 and open a browser on http://localhost:8080 you should see swagger-ui. So if you want to try it yourself you can just give it a go with hopefully no additional configuration needs.

Again I am very grateful for your support.

Regards!

gaffa avatar May 10 '13 07:05 gaffa

The problem is, to upload a file, you have to send content as MULTIPART_FORM_DATA, but you are telling swagger to send an object of type Translation. If you look at the payload being sent to the server, it looks like this:

------WebKitFormBoundaryxLYuuFjSgd2j2a2O Content-Disposition: form-data; name="translation"

{"customerName":"tony","sourceLanguage":"foo"} ------WebKitFormBoundaryxLYuuFjSgd2j2a2O Content-Disposition: form-data; name="sourceDocument"

undefined ------WebKitFormBoundaryxLYuuFjSgd2j2a2O--

Jersey is then trying to turn this String into a Translation object, expecting the content type to be MULTIPART_FORM_DATA, which it's not (it's json). So it fails.

You should receive the Translation data as a string if you need to pass in JSON and unmarshall it there, or use FORM params, which are key/value and assemble your object manually

fehguy avatar May 10 '13 13:05 fehguy

Hi again! First of all I mainly wanted to point at the fact that swagger-ui´s "click to set as parameter value" - Feature does not work in this case (tried with chrome and firefox). I have included a unit-test in the zip to illustrate a client that would consume my service. Also I have added a form under /form.html which does (pretty much) the same. As you can see everything is working fine. For the Form I needed to add a provider (TranslationDeserializer) which is pretty much what you pointed at.

https://www.dropbox.com/s/zkt41oc7bg7yqqo/swagger-jaxrs.zip

It now works from swagger-ui as well. The only thing I need to fix at this point is that swagger-ui does not insert the model into the text field...

gaffa avatar May 12 '13 11:05 gaffa

To illustrate it less complex:

These methods:

    @POST
    @Path("/works")
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation("working")
    public String working(@ApiParam("translation") Translation translation){
        return new Gson().toJson(translation);
    }

    @POST
    @Path("/oops")
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation("oops")
    public String oops(@ApiParam("translation") @FormParam("translation") Translation translation){
        return new Gson().toJson(translation);
    }

result in swagger-ui:

image

As you can see in "oops" its single-line and also the model does not get copied into the input when i click the link that says so. Shall I open another issue in swagger-ui?

gaffa avatar May 12 '13 11:05 gaffa

I will open a bug in swagger-ui and close this issue. Thanks again!

gaffa avatar May 15 '13 06:05 gaffa

Swagger-ui doesn't appear to support @FormParam or @FormDataParam for anything besides InputStream or rather, does not support POJOs.

kmadel avatar Nov 12 '14 14:11 kmadel

Take a look at the samples in swagger core for how it's supported for jersey. What are you expecting?

fehguy avatar Nov 18 '14 01:11 fehguy

what is the status of this issue. any reference to the bug created ? I am using swagger-annotation 1.5.3. I am not able to use both FormParam and FormDataParam.

school-coder avatar Dec 21 '15 11:12 school-coder