-1

Possible Duplicate:
How to upload a file using Java HttpClient library working with PHP - strange problem

I'm trying to create a script that can automatically submit a form on a website with two fields: title and description and a file input where I should upload an image. The last days I've searched every page I found on google but I can't solve my problem... I also need to post a cookie, I've made the cookie using:

connection.setRequestProperty("Cookie", cookie); //this worked

But I have problems submitting the form, first I'we tried using HttpUrlConnection, but I was unable to figure it out, now I'm trying to solve my problem using HttpClient
The html form looks like this:

<form action="submit.php" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input name="biguploadimage" type="file">
<textarea name="description"></textarea>
<input type="image" src="/images/submit-button.png">
</form>

My image is located at d:/images/x.gif Please provide me a full code because I'm new to java. O, and how to create the cookie using HttpClient ? Thanks a lot in advice!

Community
  • 1
  • 1
coolboycsaba
  • 183
  • 6
  • 13
  • 2
    So you want to use JAVA or PHP? Because your HTML form submits to PHP... – GEMI Nov 25 '11 at 08:29
  • I want to use java to submit the form. – coolboycsaba Nov 25 '11 at 08:35
  • The html form is not on my website, I need to submit something to that form each day at least once or twice and from this reason I want to make a script that fills and submits the form for me automatically – coolboycsaba Nov 25 '11 at 08:36
  • http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload (really, just search for "httpclient upload files" on Google). – Viruzzo Nov 25 '11 at 08:37

3 Answers3

1

This url might help you to solve your problem. It's not that straightforward otherwise I would have pasted the code here. upload files in java

You could also look at this question here similar question on stackoverflow

Community
  • 1
  • 1
Yanki Twizzy
  • 7,063
  • 8
  • 36
  • 64
0

There is good article with code examples: http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload

Pay attention to MultipartPostMethod. This will allow you to post file and another data in one request. How to do simple POST with many parameters described there: http://hc.apache.org/httpclient-3.x/methods/post.html

werewindle
  • 2,849
  • 14
  • 26
0

I recently did this using Spring Web MVC and Apache Commons FileUpload:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

(...)

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView uploadFile(HttpServletRequest request, HttpServletResponse response) {

        ModelAndView modelAndView = new ModelAndView("view");

        if (ServletFileUpload.isMultipartContent(request)) {
            handleMultiPartContent(request);
        }

        return modelAndView;
    }


    private void handleMultiPartContent(HttpServletRequest request) {

        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(2097152); // 2 Mb
        try {
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    File tempFile = saveFile(item);
                    // process the file
                }
            }
        }
        catch (FileUploadException e) {
            LOG.debug("Error uploading file", e);
        }
        catch (IOException e) {
            LOG.debug("Error uploading file", e);
        }
    }

    private File saveFile(FileItemStream item) {

        InputStream in = null;
        OutputStream out = null;
        try {
            in = item.openStream();
            File tmpFile = File.createTempFile("tmp_upload", null);
            tmpFile.deleteOnExit();
            out = new FileOutputStream(tmpFile);
            long bytes = 0;
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
                bytes += len;
            }
            LOG.debug(String.format("Saved %s bytes to %s ", bytes, tmpFile.getCanonicalPath()));
            return tmpFile;
        }
        catch (IOException e) {

            LOG.debug("Could not save file", e);
            Throwable cause = e.getCause();
            if (cause instanceof FileSizeLimitExceededException) {
                LOG.debug("File too large", e);
            }
            else {
                LOG.debug("Technical error", e);
            }
            return null;
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }
            catch (IOException e) {
                LOG.debug("Could not close stream", e);
            }
        }
    }

This saves the uploaded file to a temp file.

If you don't need all the low-level control over the upload, it is much simpler to use the CommonsMultipartResolver:

<!-- Configure the multipart resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="2097152"/>
</bean>

An example form in the jsp:

<form:form modelAttribute="myForm" method="post" enctype="multipart/form-data">
    <form:input path="bean.uploadedFile" type="file"/>
</form>

The uploadedDocument in the bean is of the type org.springframework.web.multipart.CommonsMultipartFile and can be accessed direcly in the controller (the multipartResolver automatically parses every multipart-request)

Adriaan Koster
  • 14,226
  • 4
  • 41
  • 56