2013-10-27 36 views
-1

我正在使用jetty服務器,並且我一直在嘗試讀取附加的圖像作爲表單添加到我收到的POST請求中。我嘗試了一些模式,但我總是得到例外。如何閱讀使用Jetty接收到的POST請求中的圖像

//Process POST requests to upload images 
private void handleImage(String target, Request baseRequest, HttpServletRequest request, 
      HttpServletResponse response) throws Exception{ 

      //Get image 
     byte[] pictureInByte = (request.getParameter("image")).getBytes(); 
     InputStream in = new ByteArrayInputStream(pictureInByte); 
     BufferedImage bImageFromConvert = ImageIO.read(in); 

      //Save to disk 
     ImageIO.write(bImageFromConvert, "jpeg", new File(
       "new-darksouls.jpg")); 



    } 

這是如何創建POST(這是在iPhone上使用Obj-C)。我在Jetty服務器上獲取請求,但無法讀取它。

//Set http client defaults 
     AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:AS_NET_BASE_URL]]; 
     [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]]; 
     [httpClient setDefaultHeader:@"Accept" value:@"application/json"]; 
     [httpClient setParameterEncoding:AFJSONParameterEncoding]; 
     [httpClient defaultValueForHeader:@"Accept"]; 

     //init http request 
     NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:route parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 

      //Append data (JSON) 
      [formData appendPartWithFileData:image 
             name:@"image" 
            fileName:@"2" 
            mimeType:@"image/jpeg"]; 
     }]; 

     //Time out 
     [request setTimeoutInterval:AS_MI_NET_TIMEOUT_INTERVAL]; 

     //Init operation 
     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request]; 

     //Set completion blocks 
     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

      //Stop indicator 
      [self stopNetworkIndicator]; 

      completion(YES, responseObject); 

     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

      [self stopNetworkIndicator]; 

      NSLog(@"%@", error); 

      completion(NO, NULL); 
     }]; 

     //Start spinning 
     [self startNetworkIndicator]; 

     //Send request 
     [operation start]; 

     //No internet, finish method 
    }else{ 
     completion(NO, NULL); 
    } 

回答

1

AFMultipartFormData類創建一個multipart request

我不認爲Jetty支持Servlet 3.0規範(它可以讓你使用request.getParts()),但是你可以使用第三方庫(Spring/Apache commons)來解析多部分請求。

在「apache commons fileupload multipart」上搜索應該找到一些例子。

如果你使用Spring,檢查出http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch16s08.html

+0

此外,'附加數據(JSON)'的評論是錯誤的 - 這不是JSON :-) – MattR

+0

呀,它改編自我對JSON其他方法 –