【问题标题】:Uploading Image From Java Desktop App to Server将图像从 Java 桌面应用程序上传到服务器
【发布时间】:2011-04-13 21:58:49
【问题描述】:

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

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 桌面应用程序编写发布多部分表单会很有用

【问题讨论】:

  • servlet 确实将图像写入文件夹......但它的大小是 0 字节......所以我猜问题出在客户端代码......仍然没有解决跨度>

标签: java image servlets iostream


【解决方案1】:

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

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

【讨论】:

  • 非常感谢您的回复....我已经更改了我的 servlet 代码,如上所示......我尝试使用 commons.apache.org/fileupload 但没有任何成功....你能指导我学习同样的好教程。
  • 看起来你现在已经搞定了服务器端。对于多部分帖子,请尝试 Apache 的 HttpClient:hc.apache.org/httpcomponents-client-ga。查看本页底部的多部分编码请求实体示例:hc.apache.org/httpcomponents-client-ga/examples.html。我认为这正是您所需要的!
  • 是的,通过 HTTPCLIENT 和 FILEUPLOAD 获得了它……非常感谢您的建议……
  • 很高兴能帮助您回答您的问题!
猜你喜欢
  • 2017-10-26
  • 2023-03-19
  • 1970-01-01
  • 2020-12-25
  • 2013-09-07
  • 2018-08-17
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
相关资源
最近更新 更多