iPhone上传图片到Servlet

时间:2013-01-29 13:04:57

标签: iphone servlets webservice-client

我正在尝试将缩略图上传到servlet。 servlet代码已经存在并与网站一起使用。

示例网址http://abcd.com/upload?param1=abc&param2=pqr

数据发布在网站上,但图片没有。

我尝试使用以下代码段上传我的图片:

代码1:

    NSData *imageData = UIImageJPEGRepresentation(imageSelect.image, 1.0);
    //NSData *imageData = UIImagePNGRepresentation(imageSelect.image);

    NSMutableData *postbody = [NSMutableData data];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary];

    NSMutableURLRequest *request= [[[NSMutableURLRequest alloc] init] autorelease];

    [request setURL:[NSURL URLWithString:strURL]];
    [request setHTTPMethod:@"POST"];        
    [request addValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    NSString *strFilename = [self getFilePath];
    NSLog(@"filename:[%@]",strFilename);

    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileing\"; filename=\"%@\"\r\n", strFilename] dataUsingEncoding:NSUTF8StringEncoding]];


    [postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:imageData]];


    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:postbody];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    //Return string always returned empty
    NSLog(@"%@", returnString);

代码2

    //NSData *imageData = UIImageJPEGRepresentation(imageSelect.image, 0.7);
    NSData *imageData = UIImagePNGRepresentation(imageSelect.image);

    NSString *filename = [self getFilePath];
    //Filename:\\var\\mobile\\Applications\\F2Dxxxx-8656-4208-B398-8D504320FC7B\\Documents\\Image_Photo.jpg        

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:strURL ]];        

    NSString *boundary = [NSString stringWithFormat:@"---------------------------14737809831466499882746641449"];

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

    NSString *contentString = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",filename];

    [request addRequestHeader:@"Connection" value:@"Keep-Alive"];
    [request addRequestHeader:@"Content-Type" value:contentType];

    NSMutableData *body = [NSMutableData data];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[contentString dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setTimeOutSeconds:60]; // 1 minute
    [request appendPostData:body];
    [request setShowAccurateProgress:YES];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestDone:)];
    [request setDidFailSelector:@selector(requestWentWrong:)];
    [request startAsynchronous];

让我知道我哪里出错了。

我也找到http://insanelycrazy.net/development/faces/viewarticle.xhtml?id=6上的文章 但由于服务器代码已准备就绪,因此无法使用此代码段。

以下是Android中使用的代码

FileInputStream fileInputStream = new FileInputStream(new File(filepath));
URL url = new URL(urlString);
Log.i("", "URL : " + url.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setChunkedStreamingMode(maxBufferSize);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
Log.i("", "Before filepath : " + filepath);
filepath = filepath.replace("/", "\\" + "\\");
Log.i("", "After filepath : " + filepath);

dos.writeBytes("Content-Disposition: form-data; name=\"fileing\";filename=\"" + filepath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
      dos.write(buffer, 0, bufferSize);
      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      progressStatus += bytesRead;
      publishProgress(progressStatus);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();

此致 萨米特

1 个答案:

答案 0 :(得分:0)

    NSURL *url = [NSURL URLWithString:YOUR URL STRING];
    NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:url];

    //adding header information:
    [postRequest setHTTPMethod:@"POST"];
    [postRequest setTimeoutInterval:60.0];
    NSString *stringBoundary = @"0xKhTmLbOuNdArY";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
    [postRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSData *imageData =UIImagePNGRepresentation(self.convertImage);


    NSMutableData *postBody = [[NSMutableData alloc] init];
    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"%@",@"Content-Disposition: form-data; name=\"userid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] valueForKey:PROFILE_DETAILS];
    [postBody appendData:[[NSString stringWithFormat:@"%@",[dic valueForKey:@"id"]] dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"%@",@"Content-Disposition: form-data; name=\"profilepic\"; filename=\"ipodfile.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[NSData dataWithData:imageData]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postRequest setHTTPBody:postBody];


    theConnection=[[NSURLConnection alloc] initWithRequest:postRequest delegate:self];

    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        receivedData = [[NSMutableData data] retain];
    }
    [postRequest release];