Scenario
Sometimes, we need to save the local iPhone resources (images for example) to the corresponding path of the server. Then you need to upload the local image to the server. In this way, you can use nsinputstream + nsurlconnection + nsmutableurlrequest to upload images.
At the beginning of the body, we need to declare some variables in the header file. h. As follows:
NSURLConnection* _aSynConnection;NSInputStream *_inputStreamForFile;NSString *_localFilePath;@property (nonatomic,retain) NSURLConnection* aSynConnection;@property (nonatomic,retain) NSInputStream *inputStreamForFile;@property (nonatomic,retain) NSString *localFilePath;
The following describes how to upload images.
At the beginning, we need to convert the data and slices we need to send to the nsdata type, and then initialize the inputstreamforfile we just declared through the class method: inputstreamwithfileatpath. Then, it is the normalized HTTP-based data upload. The Code is as follows:
-(Void) btnclickaction :( ID) sender {nsurl * serverurl; nsstring * strurl = @ "http://www.xxx.com/fileName.png"; // here the image is used as an example strurl = [strurl encoding: nsutf8stringencoding]; serverurl = [nsurl urlwithstring: strurl]; // initialize the local file path and link it to nsinputstream self. localfilepath = @ "local image path"; self. inputstreamforfile = [nsinputstream inputstreamwithfileatpath: Self. localfilepath]; // upload size nsnumber * contentlength; contentlength = (nsnumber *) [[[nsfilemanager defaultmanager] attributesofitematpath: Self. localfilepath error: NULL] objectforkey: nsfilesize]; nsmutableurlrequest * request; Request = [nsmutableurlrequest requestwithurl: serverurl]; [Request sethttpmethod: @ "put"]; [Request sethttpbodystream: Self. inputstreamforfile]; [Request setvalue: @ "image/PNG" forhttpheaderfield: @ "Content-Type"]; [Request setvalue: [contentlength description] forhttpheaderfield: @ "Content-Length"]; // request self. asynconnection = [nsurlconnection connectionwithrequest: Request delegate: Self];}
Here is the established asynchronous request, so we also need to implement the Protocol method.
-(Void) connection :( nsurlconnection *) connection response :( nsurlresponse *) aresponse {returninfodata = [[nsmutabledata alloc] init]; totalsize = [aresponse Response]; optional * httpresponse; httpresponse = (nshttpurlresponse *) aresponse; If (httpresponse. status Code/100 )! = 2) {nslog (@ "failed to save");} else {nslog (@ "saved successfully ");}}Some may ask why we need to upload files using the input stream. You can use nsdata to convert base64 for upload. There is a problem with efficiency. If we use stream mode, data is not converted, but other methods need to be converted. Therefore, we use stream mode, in the same network speed, the speed will be faster. Reference: http://blog.sina.com.cn/s/blog_7b9d64af01019qdr.html