将图像从Java桌面应用程序上传到服务器

时间:2011-04-13 21:58:49

标签: java image servlets iostream

我在客户端使用以下代码上传到服务器

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);
}

}

我已经尝试编写接收图像文件的servlet并将其保存到服务器上的文件夹中....但是失败了......这是我需要提交的学术项目的一部分作为我学位的一部分....请帮忙!!!  我想要帮助......有人可以指导我如何编写servlet ....

我尝试了以下内容:

 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();
    }
}

我继续从apache.org尝试了文件上载....并编写了以下servlet代码:

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
                         File 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();
        }
    }  

然而,我仍然对如何在客户端编写多部分代码感到困惑...我上面发布的那个不适用于我的servlet实现.....请帮助....一些链接我可以学习从java桌面应用程序编写发布多部分表单将非常有用

1 个答案:

答案 0 :(得分:0)

所以这是我的建议:不要自己编写这段代码!请改用http://commons.apache.org/fileupload/。它会为您节省很多麻烦,而且您可以快速启动并运行。我很确定问题是InputStream包含多部分边界,因此不是有效图像。

这是另一个观察结果:由于您没有对图像进行任何转换,因此无需使用ImageIO读取和写入图像字节。你最好直接从InputStream中将字节写入文件。