X

Follow us on Facebook

Sending an image from JSP to Restful Webservice using Spring Controller

Requirement: An uploaded image on client screen has to be passed to a restful web service. We'll achieve this goal using:
> JSP
> Spring 3.0.5
> Jersey Jars
> Litlle bit of ajax
> JQuery

So let's see how the maven dependency looks like for jersey jars involved: In your client side you should be having jersey-client and jersey-multipart jars

          <dependency>  
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
<exclusions>
<exclusion>
<groupId>com.sun.jersey</groupId>
<artifactId>resteasy-jaxrs</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.8</version>
</dependency>

In the JSP code
       <form id="form3" method="post" action="uploadToWS" enctype="multipart/form-data"> 
<input name="file3" id="file3" type="file" /><br />
</form>
<button value="Submit" onclick="uploadFormDataToWS()">Upload to WS</button>
<img src="#" id="imgContent2" />
<div id="imgResult2"></div>

Also have the below script:
$(document).ready(
function() {
$('#imgContent2').attr('src','resources/images/'+abc);

Add the below function (Here we retrieving the data from image file input in the form of variable file3 and are then sending to controller using ajax through oMyForm. The request is made at the mapping location uploadToWS. Response returned from the controller is then added to imgContent2)
         function uploadFormDataToWS() { 
$('#imgResult2').html('');
$('#imgContent2').html('');
var oMyForm = new FormData();
oMyForm.append("file", file3.files[0]);
$.ajax({
url : 'uploadToWS',
data : oMyForm,
dataType : 'text',
processData : false,
contentType : false,
type : 'POST',
success : function(response) {
$('#imgContent2').attr('src','resources/images/VIN.jpg');
}
});
};

and have this in the controller
 @Controller 
@RequestMapping(value = { "/uploadToWS" })
public class InventoryController {

and the below method in controller
     @RequestMapping(value = "/uploadToWS", method = RequestMethod.POST) 
public @ResponseBody
String uploadToService(MultipartHttpServletRequest request,
HttpServletResponse response) {
String reslt = "File Upload to Service Failed";
if (request instanceof MultipartHttpServletRequest) {
Iterator<String> itr = ((MultipartHttpServletRequest) request)
.getFileNames();
MultipartFile mpf = ((MultipartHttpServletRequest) request)
.getFile(itr.next());
if(wsHelper != null){
wsHelper = new WebServiceHelper();
}
reslt = wsHelper.fileUploadClient(mpf);
}
return reslt;
}
In the web service helper,
         public String fileUploadClient(MultipartFile mpf) { 
String filePath = "";
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:9280/NICUtil/rest/contact/upload");
byte[] logo = null;
try {
//logo = FileUtils.readFileToByteArray(file);
logo = mpf.getBytes();
} catch (IOException e1) {
e1.printStackTrace();
}
// Construct a MultiPart with two body parts
MultiPart multiPart = new MultiPart().bodyPart(new BodyPart(logo,
MediaType.APPLICATION_OCTET_STREAM_TYPE));
// POST the request
try {
ClientResponse response = webResource.type("multipart/mixed").post(
ClientResponse.class, multiPart);
filePath = response.getEntity(String.class);
System.out.println("id is "+filePath);
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}

On the web service provider side

Dependencies:

       <dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.8</version>
</dependency>

Inside the provider class ImageService.java

 @Path("/contact") 
public class ImageService {

have the below function:

     @POST 
@Consumes("multipart/mixed")
@Path("/upload")
public Response post(MultiPart multiPart) {
BodyPartEntity bpe = (BodyPartEntity) multiPart.getBodyParts().get(0)
.getEntity();
String id = UUID.randomUUID().toString();
boolean isProcessed = false;
String message = null;
try {
InputStream source = bpe.getInputStream();
BufferedImage bi = ImageIO.read(source);
File file = new File("E:/Goodies/svinbass/git/vinbass/theinventory/src/main/webapp/resources/images/VIN.jpg");
// storing the image to file system.
if (file.isDirectory()) {
ImageIO.write(bi, "jpg", file);
} else {
file.mkdirs();
ImageIO.write(bi, "jpg", file);
}
isProcessed = true;
} catch (Exception e) {
message = e.getMessage();
}
if (isProcessed) {
return Response.status(Response.Status.ACCEPTED)
.entity(id)
.type(MediaType.TEXT_PLAIN).build();
}
return Response.status(Response.Status.BAD_REQUEST)
.entity("Failed to process attachments. Reason : " + message)
.type(MediaType.TEXT_PLAIN).build();
}
Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment