0

I want to upload a file from jsp, handle it in my servlet and then pass the same file as Restful webservices from servlet.

Html:

<html>
<body>
    <h1>Upload File with RESTFul WebService</h1>
    <form action="rest/fileupload" method="post" enctype="multipart/form-data">
       <p>
        Choose a file : <input type="file" name="file" />
       </p>
       <input type="submit" value="Upload" />
    </form>
</body>
</html>

Servlet:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent= new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

But here, when I get the file from jsp in my own servlet, I will only get it as FileItem due to Multipart Form Data. Now how can I place that FileItem inside FileBody in order to send it as MultipartEntity. Please note that I would not want to call the Webservices directly from jsp page.

dev123
  • 11
  • 1
  • 5
  • You need to get the file content in order to send it. See http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet – Marco A. Hernandez Jun 08 '16 at 14:49
  • File content is an inputstream, now how would you post it to the webservices from servlet via FileBody? – dev123 Jun 09 '16 at 08:39
  • I think you can use InputStreamBody instead of FileBody since both implements ContentBody interface: https://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/content/ContentBody.html. In any case you could create a new temp File using the inputStream as source. – Marco A. Hernandez Jun 09 '16 at 10:02
  • ok will try it that way, thanks. – dev123 Jun 09 '16 at 12:16
  • Just wondering if the below code piece is going to process the webservices call and If I'm using InputStreamBody, whether FormDataContentDisposition will be available and whether I can get the File Name from it as shown below? @POST @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { String uploadedFileLocation = "c://uploadedFiles/" + fileDetail.getFileName(); – dev123 Jun 09 '16 at 12:17

0 Answers0