I am self teaching myself how to write rest services. I insert the input stream into my database and now I want to use the image a user might upload. I would like to give the image to its own link... How do I go about doing that with jersey? I cant not find a tutorial online.. I'm stumped on how to go about this.
Here is how i'm getting the image.. it post to my database with a few functions I did not include.
#Path("/submitinfo" )
public class SubmitName {
#POST
#Produces(MediaType.APPLICATION_XML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String post(#FormDataParam("file") InputStream uploadedInputStream, #FormParam("first") String name) {
Connection con = connection();
postName(con, name);
postPhoto(con, uploadedInputStream);
return name;
}
}
Related
I have the following code:
restTemplate.getForObject("http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg", File.class);
I especially took image which doesn't require authorization and available absolutely for all.
when following code executes I see the following stacktrace:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class java.io.File] and content type [image/jpeg]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:559)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:512)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:243)
at com.terminal.controller.CreateCompanyController.handleFileUpload(CreateCompanyController.java:615)
what do I wrong?
Image is a byte array, so you need to use byte[].class object as a second argument for RestTemplate.getForObject:
String url = "http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg";
byte[] imageBytes = restTemplate.getForObject(url, byte[].class);
Files.write(Paths.get("image.jpg"), imageBytes);
To make it work, you will need to configure a ByteArrayHttpMessageConverter in your application config:
#Bean
public RestTemplate restTemplate(List<HttpMessageConverter<?>> messageConverters) {
return new RestTemplate(messageConverters);
}
#Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
return new ByteArrayHttpMessageConverter();
}
I've tested this in a Spring Boot project and the image is saved to a file as expected.
If you simply need to get an image from a URL, Java comes with the javax.imageio.ImageIO class, which contains this method signature:
public static BufferedImage read(URL var0) throws IOException;
example use:
try {
BufferedImage image = ImageIO.read(new URL("http://www.foo.com/icon.png"));
int height = image.getHeight();
int width = image.getWidth();
} catch (IOException e) {}
The RestTemplate is expecting a class (e.g. some in-memory representation) to convert the response from the server into. For example, it could convert a response like:
{id: 1, name: "someone"}
into a class like:
class NamedThing {
private int id;
private String name;
// getters/setters go here
}
By calling:
NamedThing thing = restTemplate.getForObject("/some/url", NamedThing.class);
But, what you seem to really want to do is to take the response from the server and stream it directly to a file. Various methods exist to get the response body of your HTTP request as something like an InputStream that you can read incrementally, and then write out to an OutputStream (e.g. your file).
This answer shows how to use IOUtils.copy() from commons-io to do some the dirty work. But you need to get an InputStream of your file... A simple way is to use an HttpURLConnection. There's a tutorial with more information.
I'm using Apache Tapestry v5.3.7 and I already use the normal Tapestry upload component in a form. For a better user experience I try now to integrate Dropzone.js in a normal Tapestry page without any form. The JavaScript integration works fine. The uploaded file data are transferred to my server with a post request and I can access the request with all of its parameters.
My question is now how can I access the binary data of the uploaded file (maybe as InputStream) to save them in my system? I already injected the http request but getInputStream returns a empty stream.
Thanks for any suggestions
/** Code snippet of page java part */
...
#Inject
protected HttpServletRequest _request;
public void onActivate (String rowId) {
String fileName=_request.getParameter("file");
try {
InputStream is=_request.getInputStream();
// if I do read from is it returns -1
// :-(
doSomeSaveStuff(is); // dummy code
}
catch(Exception e) {
e.printStackTrace();
}
}
...
Here's one way to do it:
In template:
<t:form t:id="testForm" class="dropzone">
</t:form>
In page.java
#Inject
MultipartDecoder multipartDecoder;
#Component(id = "testForm")
private Form testForm;
#Inject
RequestGlobals requestGlobals;
void onSubmitFromTestForm() throws ManagerException {
System.out.println("test form invoked");
HttpServletRequest r = requestGlobals.getHTTPServletRequest();
UploadedFile u = multipartDecoder.getFileUpload("file");
The uploaded file contains what you uploaded and you can work with it the way you want.
Note: the HttpServletRequest::getParameterMap() , told me that the handle to to the file is called file which is how I know that passing file to getFileUpload makes the decoder correctly parse the multipart/post
I am using below code to get profile image of friends using Resfb. I get the response too with name id and image. Please some one help me asap on how to get the image from this data.
Code
Connection<User> myFriends = facebookClient.fetchConnection("me/friends", User.class,Parameter.with("fields", "id, name,picture"));
Response
"data":[{"id":"554603591","name":"Arjun Rao","picture":"http:\/\/profile.ak.fbcdn.net\/hprofile-ak-snc4\/211391_554603591_2022493_q.jpg"}"
Thanks
You can use restfb to parse Json-Objects:
JsonObject obj = new JsonObject(SERVER_RESPONSE);
try {
String pictureURL = obj.getString("picture");
}
catch(JsonException e) {
// key 'picture' not found
e.printStackTrace();
}
Could it be that RestFB isn't up to date in sense how Graph API returns (some objects) inside "data" object?
I managed to work-around with this custom class:
public class DataPictureHolder {
#Facebook("data")
public ProfilePictureSource picture;
}
You know how to parse the response?
If yes, just get the URL of the image, open a URLConnection and do a getInputStream() (the code for this is in this SO answer).
With the InputStream, you can save to a file or send it to the client.
I am developing my first project with Tapestry and I am about to finish, except for the images..
What do I want? I just need to display an image outside my application, example: /home/app/images/image.jpg
What did I try? I have been "googling" and reading Tapestry5 forums, I found this: http://wiki.apache.org/tapestry/Tapestry5HowToStreamAnExistingBinaryFile
I followed the steps, creating classes but I need to display the image embed on another page (so I can't use ImagePage), I tried this:
On page java class
public StreamResponse getImage() {
InputStream input = DetallesMultimedia.class
.getResourceAsStream("/home/santi/Escritorio/evolution-of-mario.jpg"); //On application, i will retrieve this from DB
return new JPEGInline(input,"hellow");
}
On page template
...
<img src="${image}" alt:image/>
...
or
...
${image}
...
Obviusly, this didn't work and I really don't know how can I do it. I read about loading the image on an event (returning the OutputStream on that event, as it's said in the HowTo linked above) but my english is so bad (I am sure you already noticed) and I don't understand well how can I do that.
Could you help me please?
Thanks you all.
I've never seen the examples as on the wiki page. Below some code on how to load an image on the classpath though using a StreamResponse.
#Inject
private ComponentResources resources;
#OnEvent(value = "GET_IMAGE_STREAM_EVENT")
private Object getProfilePic() throws Exception {
InputStream openStream = DetallesMultimedia.class.getResourceAsStream("/home/santi/Escritorio/evolution-of-mario.jpg");
byte[] imageBytes = IOUtils.toByteArray(openStream);
final ByteArrayInputStream output = new ByteArrayInputStream(imageBytes);
final StreamResponse response = new StreamResponse() {
public String getContentType() {
"image/jpegOrPngOrGif";
}
public InputStream getStream() throws IOException {
return output;
}
public void prepareResponse(Response response) {
// add response headers if you need to here
}
};
return response;
}
public String getPicUrl() throws Exception {
return resources.createFormEventLink("GET_IMAGE_STREAM_EVENT");
}
In your template:
<img src="${picUrl}"/>
I am looking for the simplest way to upload and store an image (file) to the GAE (java).
Googling for hours without any simple and clear result.
Found this link.
But I still don't know how to store an image, and how to retrieve it.
I am looking for simple servlet example.
The link your provided "How do I handle file uploads to my app?" explains how you can upload the image.
To host the images, you need to use the Datastore service to store and serve image along with your other data.
Here is a sample code. It is meant as a sketch, for how you can have your own entity (i.g. business, user, etc) have a field for an image. I ignored all error handling and recovery to simplify the code.
Declaring your entity with the image. You can imagine having other fields, e.g. tags, location, etc
#Entity
public class MyImage {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
#Persistent
private String name;
#Persistent
Blob image;
public MyImage() { }
public MyImage(String name, Blob image) {
this.name = name;
this.image = image;
}
// JPA getters and setters and empty contructor
// ...
public Blob getImage() { return image; }
public void setImage(Blob image) { this.image = image; }
}
Then when you start accepting images (watch out for cases where an image with the same name has already been uploaded in addition to the typical file upload failures). ServletFileUpload and IOUtils are classes that are part of the Apache Commons library.
// Your upload handle would look like
public void doPost(HttpServletRequest req, HttpServletResponse res) {
// Get the image representation
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(req);
FileItemStream imageItem = iter.next();
InputStream imgStream = imageItem.openStream();
// construct our entity objects
Blob imageBlob = new Blob(IOUtils.toByteArray(imgStream));
MyImage myImage = new MyImage(imageItem.getName(), imageBlob);
// persist image
PersistenceManager pm = PMF.get().getPersistenceManager();
pm.makePersistent(myImage);
pm.close();
// respond to query
res.setContentType("text/plain");
res.getOutputStream().write("OK!".getBytes());
}
And finally when you want to serve an image given its name:
Blob imageFor(String name, HttpServletResponse res) {
// find desired image
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery("select from MyImage " +
"where name = nameParam " +
"parameters String nameParam");
List<MyImage> results = (List<MyImage>)query.execute(name);
Blob image = results.iterator().next().getImage();
// serve the first image
res.setContentType("image/jpeg");
res.getOutputStream().write(image.getBytes());
}
Use the blobstore API:
The Blobstore API allows your application to serve data objects, called blobs, that are much larger than the size allowed for objects in the Datastore service. Blobs are useful for serving large files, such as video or image files, and for allowing users to upload large data files. Blobs are created by uploading a file through an HTTP request. Typically, your applications will do this by presenting a form with a file upload field to the user. When the form is submitted, the Blobstore creates a blob from the file's contents and returns an opaque reference to the blob, called a blob key, which you can later use to serve the blob. The application can serve the complete blob value in response to a user request, or it can read the value directly using a streaming file-like interface...
Easiest way to use Google App Engine Blob Store serving URL (you save instance time)
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;
...
// your data in byte[] format
byte[] data = image.getData();
/**
* MIME Type for
* JPG use "image/jpeg" for PNG use "image/png"
* PDF use "application/pdf"
* see more: https://en.wikipedia.org/wiki/Internet_media_type
*/
String mimeType = "image/jpeg";
// save data to Google App Engine Blobstore
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(mimeType);
FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
writeChannel.write(java.nio.ByteBuffer.wrap(data));
writeChannel.closeFinally();
// your blobKey to your data in Google App Engine BlobStore
BlobKey blobKey = fileService.getBlobKey(file);
// THANKS TO BLOBKEY YOU CAN GET FOR EXAMPLE SERVING URL FOR IMAGES
// Get the image serving URL (in https:// format)
String imageUrl =
ImagesServiceFactory.getImagesService().getServingUrl(
ServingUrlOptions.Builder.withBlobKey(blobKey
).secureUrl(true));