working with files
Does not work within eclipse (likely due to the classpath) if you figure out why, please let me know!
Please use the embedded tomcat, run:
mvn clean package
then
On Mac and Linux:
$ sh target/bin/webapp
On Windows:
C:/> target/bin/webapp.bat
Please use the embedded tomcat, run:
mvn clean package
then
On Mac and Linux:
$ sh target/bin/webapp
On Windows:
C:/> target/bin/webapp.bat
Add new dependency to your pom.xml:
<dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-multipart</artifactId> <version>2.14</version> </dependency>
Add another init param to your servletThe service to upload the file<init-param> <param-name>jersey.config.server.provider.classnames</param-name> <param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature</param-value> </init-param>
package services; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; @Path("/file") public class UploadFileService { @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { String uploadedFileLocation = "/temp/" + fileDetail.getFileName(); // save it writeToFile(uploadedInputStream, uploadedFileLocation); String output = "File uploaded to : " + uploadedFileLocation; return Response.status(200).entity(output).build(); } // save uploaded file to new location private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) { try { OutputStream out = new FileOutputStream(new File( uploadedFileLocation)); int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }