2

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

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);
        }
    }

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

4

1 回答 1

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]];
    }
于 2013-02-28T10:19:48.380 回答