How can i upload file and other parameter using NSURLConnection

前端 未结 1 949
独厮守ぢ
独厮守ぢ 2021-01-16 10:52

I am using NSURLConnection to send same data (NSString) to the server and i would like to add with them an image or a file so what\'s the value of

相关标签:
1条回答
  • 2021-01-16 11:48

    You need to pass the data into as stream type in your server

    public InsertImage(Stream stream)
    

    Something like that then parse the stream type.

    This is how to build your request using some boundaries

    - (NSURLRequest *)buildRequest:(NSData *)paramData fileName:(NSString *)name {
        NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
        NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
        [request setURL:self.url];
        [request setHTTPMethod:self.method];
    
        NSString *boundary = @"0xKhTmLbOuNdArY";
        NSString *endBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary];
    
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; charset=%@; boundary=%@", charset, boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
        NSMutableData *tempPostData = [NSMutableData data]; 
        [tempPostData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
        // Sample Key Value for data
        [tempPostData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"Key_Param"] dataUsingEncoding:NSUTF8StringEncoding]];
        [tempPostData appendData:@"Value_Param"] dataUsingEncoding:NSUTF8StringEncoding]];
        [tempPostData appendData:[endBoundary dataUsingEncoding:NSUTF8StringEncoding]];
    
        // Sample file to send as data
        [tempPostData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", name] dataUsingEncoding:NSUTF8StringEncoding]];
        [tempPostData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [tempPostData appendData:paramData];
        [tempPostData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:tempPostData];
        return request;
    }
    

    You should get the stream type data on your server side and parse it, you can get the value base on the Key you pass e.g. Key_Param, and the name(fileName)of the file you send.

    0 讨论(0)
提交回复
热议问题