Created
June 3, 2018 23:55
-
-
Save gorlok/656e0f87842796e80203eff3f510ed6a to your computer and use it in GitHub Desktop.
JAX-RS EE7 Upload File (Json Base64)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.util.Base64; | |
import java.util.UUID; | |
import javax.json.JsonObject; | |
import javax.ws.rs.Consumes; | |
import javax.ws.rs.GET; | |
import javax.ws.rs.POST; | |
import javax.ws.rs.Path; | |
import javax.ws.rs.PathParam; | |
import javax.ws.rs.Produces; | |
import javax.ws.rs.core.Context; | |
import javax.ws.rs.core.MediaType; | |
import javax.ws.rs.core.Response; | |
import javax.ws.rs.core.Response.ResponseBuilder; | |
import javax.ws.rs.core.UriBuilder; | |
import javax.ws.rs.core.UriInfo; | |
@Path("file") | |
public class FileResource { | |
final static String FILES_PATH = "/tmp"; | |
@GET | |
@Path("ping") | |
public String ping() { | |
return "ping " + System.currentTimeMillis(); | |
} | |
@POST | |
@Path("upload") | |
@Consumes(MediaType.APPLICATION_JSON) | |
public Response receiveJSON(JsonObject json, @Context UriInfo uriInfo) | |
throws IOException { | |
String id = convertFile(json.getString("file")); | |
//String fileName = json.getString("file_name"); | |
//String mimeType = json.getString("mime_type"); | |
UriBuilder builder = uriInfo.getAbsolutePathBuilder(); | |
builder.path(id); | |
return Response.created(builder.build()).build(); | |
// http://localhost:8080/helloworld-ee7/api/file/upload/5e774c4e-ae55-4291-a302-74396e29d842 | |
} | |
//Convert a Base64 string and create a file | |
private String convertFile(String dataBase64) | |
throws IOException{ | |
byte[] bytes = Base64.getDecoder().decode(dataBase64); | |
String uuid = UUID.randomUUID().toString(); | |
File file = new File(FILES_PATH + File.separator + uuid); | |
try (FileOutputStream fos = new FileOutputStream(file)) { | |
fos.write(bytes); | |
fos.flush(); | |
} | |
return uuid; | |
} | |
@GET | |
@Path("/upload/{uuid}") | |
@Produces("application/pdf") | |
public Response getFile(@PathParam("uuid") String uuid) { | |
File file = new File(FILES_PATH + File.separator + uuid); | |
ResponseBuilder response = Response.ok((Object) file); | |
response.header("Content-Disposition", | |
"attachment; filename=" + "document.pdf"); | |
return response.build(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment