将图像从Objective-c上传到服务器

时间:2018-05-29 12:58:12

标签: java ios objective-c xcode

您好我的目的是形成objective-c和xcode 9.服务器上的代码可以工作,因为我可以从Android上传好的文件图像。 我尝试做了一些更改,但我在服务器上遇到了同样的错误。

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"my-url"]];

NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

NSString *connection = @"Keep-Alive";
[request addValue:connection forHTTPHeaderField:@"Connection"];

NSString *boundary = @"*****";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

NSMutableData *body = [NSMutableData data];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename=\"%@\"\r\n",newName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];
NSLog(@"Request body %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);

NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
NSLog(@"%@", [request allHTTPHeaderFields]);

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
    if(data.length > 0) {
        //success
        NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Response %@",responseString);
        NSError *error;
        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
        if(error == nil){
            if([[responseDictionary objectForKey:@"ok"]boolValue]) {
                NSString *fileURL = [[responseDictionary objectForKey:@"file"] objectForKey:@"url_download"];
                NSLog(@"File URL %@", fileURL);
            } else {
                NSLog(@"Could Not upload file ");
            }
        }
    }
}] resume];

以下代码包含服务器中应解码图像的方法。当我从Android代码发送相同的多部分表单时,该代码工作正常。

@POST
@Path("/uploadFile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {

    String output = "-1";
    if (contentDispositionHeader.getFileName().split("~@~").length > 2) {

        String codMun = contentDispositionHeader.getFileName().split("~@~")[0];
        String fileName = contentDispositionHeader.getFileName().split("~@~")[1] + "~@~"
                + contentDispositionHeader.getFileName().split("~@~")[2];
        String filePath = SERVER_UPLOAD_LOCATION_FOLDER + "/resources/" + fileName;

        if (fileInputStream != null) { 
            if (saveFile(fileInputStream, filePath) < 0) {
                Response.status(200).entity("{\"error\":\"-2\"}").build();
            }
            output = "{\"error\":\"0\"}";

        } else {
            return Response.status(200).entity("{\"error\":\"-1\"}").build();
        }
    }

    return Response.status(200).entity(output).build();
}


private int saveFile(InputStream uploadedInputStream, String serverLocation) {

    int flagExit = -1;
    try {

        OutputStream outpuStream = new FileOutputStream(new File(serverLocation));

        if (outpuStream != null) {

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = uploadedInputStream.read(bytes)) != -1) {
                outpuStream.write(bytes, 0, read);
            }
            outpuStream.flush();
            outpuStream.close();
            flagExit = 1;
        }
    } catch (IOException e) {
        logger.error("Error Output : ", e);
        flagExit = -3;
        e.printStackTrace();
    }
    return flagExit;

}

1 个答案:

答案 0 :(得分:1)

查看代码,我稍微简化了一下(删除了不相关的行并重新排列),我能够发现一些错误:

  • 在身体开始时你有一个空行,你不需要它(它会被库自动插入)。
  • 你有&#34; - &#34;在boundtringWithFormat之前或之后,你不需要它。你可以把&#34; - &#34;如果你愿意,在边界内,但你不必。所有边界都很重要。
  • 您在bodyData内部之前缺少一个空行。您的数据在&#34; Content-Disposition&#34;之后的下一行开始,但中间需要一个空行(只是&#34; \ r \ n&#34;)。

小调:

  • 您应该为图片添加第二个内容类型标题。由于你有JPEG,它应该是&#34; Content-Type:image / jpeg \ r \ n&#34;在&#34; Content-Disposition之后:......&#34;。
  • 这是多余的:[body appendData:[NSData dataWithData:imageData]];,因为[body appendData:imageData];也适用。

检查此答案:https://stackoverflow.com/a/23517227/1009546

它是一个很好的例子,它应该是什么样的,你可以使用&#34; nc -l localhost 8000&#34;进行调试。如果您将URL设置为&#34; http://localhost:8000&#34;

,则iOS模拟器会发送正确的内容命令