1

Good afternoon, I hope you can help me. I'm trying to send a form with the xhr object. I have this in my html page

<form action="" method="post" enctype="multipart/form-data">
    <p>
        Choose a file : <input type="file" name="archivos"/>
    </p>
    <input type="submit" value="Upload" onclick="sendForm(this.form)"/>
</form>

the action of the form I'm doing with the xhr object, in my javascript file the following

function sendForm(form) {
    var formData = new FormData(form);
    var xhr = new XMLHttpRequest();
    xhr.open('POST','http://localhost:8080/project/webresources/generic/archivo',false);
    xhr.send(formData);
}

the previous url's of my archive rest Rest In my file I have the following:

@POST
@Path("/archivo")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json")
public void uploadFilebyRest(
        FormDataMultiPart multiPart)
        throws IOException{
    List<FormDataBodyPart> fields = multiPart.getFields("archivos");
    for (FormDataBodyPart field : fields) {
        handleInputStream(field.getValueAs(InputStream.class));
    }
}

then with the method handleInputStream I receive the InputStream achievement and create the file on my hard drive

private String handleInputStream(InputStream uploadedInputStream) throws IOException {
    byte[] Arraybytes = IOUtils.toByteArray(uploadedInputStream);
    InputStream input = new ByteArrayInputStream(Arraybytes);
    int data = input.read();
    String uploadedFileLocation = "c://Imagenes/Foto.jpg";
    OutputStream out;
    out = new FileOutputStream(new File(uploadedFileLocation));
    while (data != -1) {
        out.write(data);
        data = input.read();
    }
    out.flush();
    out.close();
    input.close();
    return "";

}   

All the above code works for me using java EE 6 and Glassfish 3 Someone tell me why I could not work when using Java EE 7 and Glassfish 4 I have the following to my log

415 Unsupported Media Type help me! thanks.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
trivas
  • 11
  • 2

1 Answers1

0

Glassfish 4 includes Jersey 2.x which works differently from the 1.x branch. In order to get multipart to work you need to register MultiPartFeature in your jax-rs Application or ResourceConfig class.

https://jersey.java.net/documentation/latest/media.html#multipart

A word of caution, however. There is a Jersey/CDI bug in Glassfish 4 that causes several exceptions when you deploy an application that uses MultiPartFeature. The bug is fixed in the Glassfish promoted builds starting with b08.

Baldy
  • 2,002
  • 14
  • 14