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

问题描述:

我使用在客户端下面的代码上传到服务器图片上传从Java桌面应用程序到服务器

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实现工作.. ...请帮助....一些链接,我可以学习写作ng从Java桌面应用发布多部分形式将是有用的

+0

该servlet确实将文件写入文件夹....但它的大小是0字节....所以我想问题在于客户端代码....仍然未解决 – knurdy 2011-04-13 23:20:30

所以这里是我的建议:不要自己写这个代码!改为使用http://commons.apache.org/fileupload/。它会为你节省很多头痛,并且你会很快起来跑步。我很确定问题在于InputStream包含多部分边界,因此不是有效的图像。

下面是另一个观察:由于您没有对图像进行任何转换,因此不需要使用ImageIO读写图像字节。您最好将InputStream中的字节直接写入文件。

+0

非常感谢您的回复....我已经改变了我的servlet代码,如上所述......我尝试使用http://commons.apache.org/fileupload/,但没有任何成功....你可以指导我很好的教程对于相同的。 – knurdy 2011-04-13 23:15:17

+0

看起来你现在已经弄清楚服务器端了。对于多部分帖子,请尝试Apache的HttpClient:http://hc.apache.org/httpcomponents-client-ga/。查看本页底部的Multipart编码请求实体示例:http://hc.apache.org/httpcomponents-client-ga/examples.html。我认为这正是你需要的! – stevevls 2011-04-14 07:32:30

+0

是的HTTPCLIENT和FILEUPLOAD ....非常感谢你的建议。 – knurdy 2011-04-14 13:01:08