开发者

Uploading Image From Java Desktop App to Server

I am using the following code on the client side to upload to the server

public class UploaderExample{

private static final String Boundary = "--7d021a37605f0";

public void upload(URL url, List<File> files) throws Exception
{
    HttpURLConnection theUrlConnection = (HttpURLConnection) url.openConnection();
    theUrlConnection.setDoOutput(true);
    theUrlConnection.setDoInput(true);
    theUrlConnection.setUseCaches(false);
    theUrlConnection.setChunkedStreamingMode(1024);

    theUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
            + Boundary);

    DataOutputStream httpOut = new DataOutputStream(theUrlConnection.getOutputStream());

    for (int i = 0; i < files.size(); i++)
    {
        File f = files.get(i);
        String str = "--" + Boundary + "\r\n"
                   + "Content-Disposition: form-data;name=\"file" + i + "\"; filename=\"" + f.getName() + "\"\r\n"
                   + "Content-Type: image/png\r\n"
                   + "\r\n";

        httpOut.write(str.getBytes());

        FileInputStream uploadFileReader = new FileInputStream(f);
        int numBytesToRead = 1024;
        int availableBytesToRead;
        while ((availableBytesToRead = uploadFileReader.available()) > 0)
        {
            byte[] bufferBytesRead;
            bufferBytesRead = availableBytesToRead >= numBytesToRead ? new byte[numBytesToRead]
                    : new byte[availableBytesToRead];
            uploadFileReader.read(bufferBytesRead);
            httpOut.write(bufferBytesRead);
            httpOut.flush();
        }
        httpOut.write(("--" + Boundary + "--\r\n").getBytes());

    }

    httpOut.write(("--" + Boundary + "--\r\n").getBytes());

    httpOut.flush();
    httpOut.close();

    // read & parse the response
    InputStream is = theUrlConnection.getInputStream();
    StringBuilder response = new StringBuilder();
    byte[] respBuffer = new byte[4096];
    while (is.read(respBuffer) >= 0)
    {
        response.append(new String(respBuffer).trim());
    }
    is.close();
    System.out.println(response.toString());
}

public static void main(String[] args) throws Exception
{
    List<File> list = new ArrayList<File>();
    list.add(new File("C:\\square.png"));
    list.add(new File("C:\\narrow.png"));
    UploaderExample uploader = new UploaderExample();
    uploader.upload(new URL("http://systemout.com/upload.php"), list);
}

}

I have tried writing the servlet that receives the image file and saves it to a folder on the server....but have failed miserably...This is part of an academic project i need to submit as part of my degree....Please Help!!! I want help ...can someone guide me on how the servlet will be written....

I tried the following:

 response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

        InputStream input = null;
        OutputStream output = null;

        try {
            input = request.getInputStream();
            output = new FileOutputStream("C:\\temp\\file.png");

            byte[] buffer = new byte[10240];
            for (int length = 0; (length = input.read(buffer)) > 0  ; ) {
                output.write(buffer, 0, length);
            }
        }
        catch(Exception e){
        out.println(e.getMessage());
    }
        finally {
            if (output != null) {
                output.close();
            }
            if (input != null) {
                input.close();
            }
        }

        out.println("Success");
    }
    catch(Exception e){
        out.println(e.getMessage());
    }
    finally {
        out.close();
    }
}

I went ahead and tried the fileupload from apache.org....and wrote the following servlet code:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            out.println(1);
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {


                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                // Parse the request
                List /* FileItem */ items = upload.parseRequest(request);

                // Process the uploaded items
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField()) {
                        //processFormField(item);
                    } else {
                        //processUploadedFile(item);
                        String fieldName = item.getFieldName();
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        boolean isInMemory = item.isInMemory();
                        long sizeInBytes = item.getSize();

                        //write to file
                         Fi开发者_StackOverflow中文版le uploadedFile = new File("C:\\temp\\image.png");
                         item.write(uploadedFile);

                         out.println("Sucess!");
                    }
                }

            } else {
                out.println("Invalid Content!");
            }
        } catch (Exception e) {
            out.println(e.getMessage());
        } finally {
            out.close();
        }
    }  

However i am still confused on how to write the multipart code on the client side...the one i posted above is not working with my servlet implementation.....help please....some links where i can learn writing posting multipart form from java desktop app would be useful


So here's my recommendation: don't write this code yourself! Use http://commons.apache.org/fileupload/ instead. It will save you a lot of headaches, and you'll be up and running quite quickly. I'm pretty sure that problem is that the InputStream contains the multi-part boundaries, and is thus not a valid image.

Here's another observation: since you're not doing any transformations on the image, there's no need to read and write the image bytes using ImageIO. You're better off writing the bytes straight from the InputStream to the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜