2016-07-28 74 views

回答

0

雖然使用base64字符串是一個選項,但有更好的方式去發送JAX-RS Web服務中的文件。我個人建議創建一個方法來偵聽用戶POST HTTP表單。這種形式可以真正包含您需要發送的所有信息以及標識符。

這與我將用於此類型的Web服務的方法定義類似。它與Jersey兼容,它允許用戶通過基本的HTML表單或任何POST請求發送文件。我強烈建議看看構建Java Web服務的this article。它不包括「文件上傳」方面,但它非常有用,它幫助我瞭解更多關於Java Web服務功能的更多信息。

@POST 
    @Path("/upload") 
    @Consumes(MediaType.MULTIPART_FORM_DATA) 
    @Produces("text/html") 
    public Response uploadFile(
     @FormDataParam("username") String username, 
     @FormDataParam("password") String password, 
     @FormDataParam("title") String title, 
     @FormDataParam("file") InputStream fileInputString, 
     @FormDataParam("file") FormDataContentDisposition fileInputDetails) { 
    String status = null; 

    String fileLocation = "/home/user/uploadtest/test.png; 
    NumberFormat myFormat = NumberFormat.getInstance(); 
    myFormat.setGroupingUsed(true); 
    // Save the file 
    try { 
    OutputStream out = new FileOutputStream(new File(fileLocation)); 
    byte[] buffer = new byte[1024]; 
    int bytes = 0; 
    long file_size = 0; 
    while ((bytes = fileInputString.read(buffer)) != -1) { 
     out.write(buffer, 0, bytes); 
     file_size += bytes; 
    } 
    out.flush(); 
    out.close(); 


    status = "File has been uploaded to:" + fileLocation; 
    } catch (IOException ex) { 
     System.err.println("Unable to save file: " + fileLocation); 
     ex.printStackTrace(); 
    } 


    return Response.status(200).entity(status).build(); 
} 
相關問題