I have a java servlet which accepts an image a user uploads to my web app.
I have another server (running php) which will host all the images. How can I get an image from my jsp server to my php server? The flow would be something like:
public class ServletImgUpload extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
// get image user submitted
// try sending it to my php server now
// return success or failure message back to user
}
}
Thanks
First of all, why don’t you just submit the form directly to that PHP script?
If this is somehow not an option and you really need to submit the form to the servlet, then first create a HTML form like following in the JSP:
In the servlet which listens on an
url-patternof/upload, you have 2 options to handle the request, depending on what the PHP script takes.If the PHP script takes the same parameters and can process the uploaded file the same way as the HTML form has instructed the servlet to do (I would still rather just let the form submit directly to the PHP script, but anyway), then you can let the servlet play for a transparent proxy which just transfers the bytes immediately from the HTTP request to the PHP script. The
java.net.URLConnectionAPI is useful in this.If the PHP script takes different or more parameters (again, I would rather just alter the HTML form accordingly so that it can directly submit to the PHP script), then you can use use Apache Commons FileUpload to extract the uploaded file and Apache HttpComponents Client to submit the uploaded file to the PHP script as if it’s submitted from a HTML form.
See also: