代码之家  ›  专栏  ›  技术社区  ›  B T

如何从Java中实现图像数据的表象

  •  3
  • B T  · 技术社区  · 14 年前

    嘿,我已经试过研究如何从Java发布数据,而且似乎没有什么我想做的。基本上,有一种将图像上传到服务器的形式,而我想要做的是将图像发布到同一个服务器——但从Java。它还需要有正确的参数名(无论表单输入的名称是什么)。我还想返回这个方法的响应。

    我搞不懂为什么这件事这么难找到,因为这件事似乎很基本。

    编辑----添加的代码

    基于Balusc向我展示的一些东西,我创建了以下方法。它仍然不起作用,但它是我迄今为止获得的最成功的东西(似乎向另一台服务器发布了一些内容,并返回某种响应-但我不确定是否正确地得到了响应):

    edit2——根据balusc的反馈添加到代码中

    edit3——发布基本有效的代码, 但似乎有问题 :

     ....
    
     FileItemFactory factory = new DiskFileItemFactory();
    
     // Create a new file upload handler
     ServletFileUpload upload = new ServletFileUpload(factory);
    
     // Parse the request
     List<FileItem> items = upload.parseRequest(req);
    
     // Process the uploaded items
     for(FileItem item : items) {
         if( ! item.isFormField()) {
             String fieldName = item.getFieldName();
             String fileName = item.getName();
             String itemContentType = item.getContentType();
             boolean isInMemory = item.isInMemory();
             long sizeInBytes = item.getSize();
    
             // POST the file to the cdn uploader
             postDataRequestToUrl("<the host im uploading too>", "uploadedfile", fileName, item.get());
    
         } else {
             throw new RuntimeException("Not expecting any form fields");
         }
     }
    
    ....
    
    // Post a request to specified URL. Get response as a string.
    public static void postDataRequestToUrl(String url, String paramName, String fileName, byte[] requestFileData) throws IOException {
     URLConnection connection=null;
    
     try{
         String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
         String charset = "utf-8";
    
         connection = new URL(url).openConnection();
         connection.setDoOutput(true);
         connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
         PrintWriter writer = null;
         OutputStream output = null;
         try {
             output = connection.getOutputStream();
             writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!
    
             // Send binary file.
             writer.println("--" + boundary);
             writer.println("Content-Disposition: form-data; name=\""+paramName+"\"; filename=\"" + fileName + "\"");
             writer.println("Content-Type: " + URLConnection.guessContentTypeFromName(fileName));
             writer.println("Content-Transfer-Encoding: binary");
             writer.println();
    
             output.write(requestFileData, 0, requestFileData.length);
             output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
    
             writer.println(); // Important! Indicates end of binary boundary.
    
             // End of multipart/form-data.
             writer.println("--" + boundary + "--");
         } finally {
             if (writer != null) writer.close();
             if (output != null) output.close();
         }
    
         //*  screw the response
    
         int status = ((HttpURLConnection) connection).getResponseCode();
         logger.info("Status: "+status);
         for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
             logger.info(header.getKey() + "=" + header.getValue());
         }
    
     } catch(Throwable e) {
         logger.info("Problem",e);
     } 
    

    }

    我可以看到这个代码在上传文件,但是只有 之后 我把猫关了。这让我相信我会留下某种联系。

    这是有效的!

    2 回复  |  直到 14 年前
        1
  •  4
  •   Community CDub    8 年前

    您要使用的核心API是 java.net.URLConnection . 然而,这是相当低的水平和冗长。你想了解 HTTP specifics 并将其考虑在内( headers ,等等)。你可以在这里找到 a related question with lot of examples .

    更方便的HTTP客户端API是 Apache Commons HttpComponents Client . 你可以找到一个例子 here .


    更新 :根据您的更新:您应该将响应读取为字符流,而不是二进制流,并尝试将字节强制转换为字符。这不管用。前往 正在收集HTTP响应信息 用示例部分链接问题。它应该是这样的:

    BufferedReader reader = null;
    StringBuilder builder = new StringBuilder();
    
    try {
        reader = new BufferedReader(new InputStreamReader(response, charset));
        for (String line; (line = reader.readLine()) != null;) {
            builder.append(line);
        }
    } finally {
        if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
    }
    
    return builder.toString();
    

    更新2: 根据你的第二次更新。看到你如何继续附加读/写流,我认为是时候学习 basic Java IO :)好吧,这部分也在相关问题中得到了回答。你想用 Apache Commons FileUpload 解析一个 multipart/form-data 在servlet中请求。如何使用它也在链接的问题中描述/链接。看看底部的 上传文件 章。顺便说一下,Content-Length头将返回零,因为您没有显式地设置它(而且如果不在内存中缓冲整个请求,也不能这样做)。


    更新3:

    我可以看到这个代码上传文件,但只有在我关闭Tomcat之后。这让我相信我会留下某种联系。

    你需要 关闭 这个 OutputStream 用它将文件写入磁盘。再次,阅读上面链接的基本Java IO教程。


        2
  •  1
  •   Nicolas78    14 年前

    你试过什么?如果你为HTTP邮政Java谷歌,出现几十页-他们怎么了?这一个, http://www.devx.com/Java/Article/17679/1954 例如,看起来很体面。