在写入服务器中的文件时,作为HTTP POST发送的图像被损坏

时间:2013-02-28 10:03:59

标签: ios objective-c http post http-post

我使用以下代码将图像发布到我的服务器。

NSString *localCacheDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Downloads"];
NSString *localPathToSaveFile = [localCacheDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"lion.jpg"]];

NSMutableString *urlForUploadingAttachment = MY_SERVER_URL;

NSData *myData = [NSData dataWithContentsOfFile:localPathToSaveFile];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

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

// add image data
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:localPathToSaveFile], 1.0);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"lion.jpg"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

// setting the body of the post to the reqeust
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:[NSURL URLWithString:urlForUploadingAttachment]];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);

在服务器端.net应用程序中,我将文件写为

    public void SaveAttachment(string filePath, string fileName)
    {
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }
        string fullFilePath = filepath + "\\" + fileName;
        using (Stream file = File.OpenWrite(fullFilePath))
        {
            CopyStream(Request.InputStream, file);
            try
            {
                file.Close();
            }
            catch (Exception ex) { }
        }
    }

    public void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[8 * 1024]; int len;
        while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, len);
        }
    }

但是服务器写入的文件已损坏。即使文件被写入,我也无法打开或预览它。文件大小也符合预期。但是,当我双击图像时,我收到文件损坏,损坏或太大的消息。这是什么问题?有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

对于POST Method的图片发布,这里简单的代码根据您的要求使用它:

NSString  *imgPath = fullPathOfYourImage;
    if([[NSFileManager defaultManager] fileExistsAtPath:imgPath])
    {
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];                                                        
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"photo\"; filename=\"YourImageName.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
                                                                                                               ^..YourImageName….^

        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithContentsOfFile:imgPath]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    }