Send image as API response - java

I need to send images as API response.I created a response but i still cant not send the image.I am using play framework with java.
Http.Response response = new Http.Response();
response.setContentType("image/jpeg");
Thanks.

Do not really know what version of play are you using but this should work for 2.X
public static Result returnImage(){
return ok(new File("public/img/1.jpg")).as("image/jpg");
}
Here you can see that ok() can receive a File as a parameter. To check all the options you can go to Play Framework JavaDocs.
Hope it helps!

Previous answer is correct, however if image is large, I would suggest using chunks and streams:
public Result send() throws FileNotFoundException {
FileInputStream fis = new FileInputStream(new File("some_path/test.jpeg"));
response().setContentType("image/jpeg");
return ok(fis);
}

Related

How to return a video to postman

I'm doing a project of mine something like lets say youtube I've done the uploading videos part but I'm stuck on how can I playback those videos to Postman?
I've tried making the return type MultipartFile class and just returning the file but it doesn't seems to work.
#RestController
public class VideoController {
#PostMapping(value = "/upload")
public void uploadVideo(#RequestParam("video") MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
File newVideo = new File("D:\\test\\" + file.getName() + ".mp4");
FileOutputStream fos = new FileOutputStream(newVideo);
fos.write(bytes);
}
}
I don't think Postman support video streaming. Regardless, in order to stream video your VideoController would need to have a GetMapping method that supports range requests which is a non-trivial coding task.
You should take a look at the community project Spring Content. This project is an abstraction over Storage and provides a range of Storage implementations including the good old Filesystem. Importantly, it also supports video streaming out of the box as this post describes.
NB: Current version of Spring Content is 0.8.0.

How to download (stream) large (generated) file in Micronaut

In my app I'm generating large pdf/csv files. I'm wondering Is there any way to stream large files in Micronaut without keeping it fully in memory before sending to a client.
You can use StreamedFile, eg:
#Get
public StreamedFile download() {
InputStream inputStream = ...
return new StreamedFile(inputStream, "large.csv");
}
Be sure to check the official documentation about file transfers.

Java :Not able to download spreadsheet using google drive API

I am trying to download a file from the drive using google drive api
Steps to reproduce :
Step 1:
Click on :https://developers.google.com/drive/v3/reference/files/export#try-it
Step 2:
I have provided fileid and mimetype
I gave fileid and mime type as "application/vnd.google-apps.spreadsheet" and click on execute.i got this error:
"code":403,
"message":"Export requires alt=media to download the exported content."
public static void downloadFile(Drive service,String fileId) throws IOException{
OutputStream outputStream = new ByteArrayOutputStream();
//OutputStream outputStream = new FileOutputStream("/Users/xxxxx/Downloads/driveFile.xls");
//service.get
service.files().export(fileId,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
.executeMediaAndDownloadTo(outputStream);
}
Based on the error you are getting...
https://developers.google.com/drive/v3/web/manage-downloads
Try adding "?alt=media" to your GET request. My guess is you are missing something in the input parameters or possibly do not have access to the media (not logged in maybe?). I can't help more without seeing the actual code you are attempting to call, or the request you are making.

Android: Showing Spanish (among other) characters read from file

I know there are a lot of questions similar to this all around SO, but they either provide a very case-specific solution that I don't get to adapt to my issue or simply don't seem to work at all.
I have a multi-language app that downloads certain information from the internet and stores it into a file for later usage. This is how the storage is done:
public static void writeStringToFile(String string, File file)
throws IOException {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(string.getBytes("UTF-8"));
outputStream.close();
}
But later, when the spanish version of the file is read, the app displays the special characters, like ñ, as the black diamond with the question mark inside I-ve tried to:
Download the information in my computer to check that the file is fine and put it manually in the app so that it reads from it instead of downloading it itself. The file is fine, but the app shows no change.
Replace the argument of getBytes by "ISO 8859-1", but the only difference in the result is that the weird character is this time the regular question mark.
Copy the file, once downloaded, from the device to the computer to check if it was fine, and it was already wrong (there are "empty square" characters shown in place of the question marks, that are not shown if I wget the file).
So I'm almost sure that the problem is in how I write the file since it gets out of the server fine but is stored wrong. But I have been so much time looking at the method and I can't find what the problem is...any clues?
EDIT: This is how I download the information.
public static InputStream performGetRequest(String uri)
throws IOException, URISyntaxException, ServerIsCheckingException {
HttpResponse response;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(uri));
response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 409) {
throw new ServerIsCheckingException();
}
else {
return response.getEntity().getContent();
}
}
To convert it to a String object that I later pass to the method writeStringToFile, I use
public static String inputStreamAsString(InputStream is) throws IOException {
java.util.Scanner s = new java.util.Scanner(is);
String ret;
ret = s.useDelimiter("\\A").hasNext() ? s.next() : "";
return ret;
}
I also thought that writeStringToFile could be the problem, but I tried another alternative which specifies UTF-8 to be used and didn't work either.
You'll have to make sure that the document you are trying to write is being read in the same charset. In your case, if the document you're downliading is in spanish, it will probably be written in UTF-8 or ISO-8859-1, so you'll have to set the corresponding enconding both in the reading and writing.
You might use HttpProtocolParams.setContentCharset() to set the corresponding charset to the BasicHttpParams object.
This might help:
Android Java UTF-8 HttpClient Problem

Generating a dynamic file and download it in GWT

I am developing a GWT application. This application is running in a server. Well, I implement a button which calls a method that generates a local file in server side. However I would like to download/generate this file in client side. How could I do this in GWT?
Thanks
In our project we created a file on server on demand. When the file has been successful created we send notification to browser and created a link.
See servlet code:
public class DownloadServlet extends HttpServlet {
private FileManager fileManager;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String encodedFileName = req.getRequestURI().substring(
req.getContextPath().length() + req.getServletPath().length() + 1);
String decodedFileName = URLDecoder.decode(encodedFileName, "utf-8");
File downloadableFile = fileManager.toFile(decodedFileName);
ServletOutputStream os = resp.getOutputStream();
try {
InputStream is = FileUtils.openInputStream(downloadableFile);
try {
IOUtils.copy(is, os);
} finally {
is.close();
}
} finally {
os.close();
}
}
}
private native void Download(String filename, String text)/*-{
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom); }-*/;
Use JSNI method inside GWT code , provide the file name you want to download in addition to JSON string as text (String) , this method will download a file with specified content in text variable to client browser.
Current situation is, that not all browsers are able to work with local file system, so there is no universal solution in GWT. Also as far as I know FilesSstem API is not finished.
As alternative you can keep using serverside generated files, or use Flash plugin to generate and store files (you will have to create a Flash app, and create some API to control it from GWT).
You should definitely have a look at Aki Miyazaki’s HTML5 file download code for GWT.
It works on the client side as you requested.
AFAIK, as of now, it only works in Chrome, but this is supposed to change as other browsers implement the download attribute.
You can do that using Data URIs:
Make your GWT RPC method return the file content or the data to generate the file.
On the client side, format a Data URI with the file content received or generate the data content.
Use Window.open to open a file save dialog passing the formatted DataURI.
Take a look at this reference, to understand the Data URI usage:
Export to csv in jQuery

Categories