1, File Upload:
?重要: When a user wants to transfer a client-side file to the server, it is time to POST pass the file to the server using the request method, NSURLSessionUploadTask file upload task.
1-1, Technical points:
?重要: ① sets the request header information, tells the server this network request is to send the file to the server, ② splicing the file to upload the data, the stitching process must strictly follow the file upload format, otherwise, the file upload will fail.
1-2, File Upload format: 1, set the request header information:
?重要: Set the request header to tell the server that this is a file upload operation.
2. Set file parameters:
?重要: Set the request body, convert the file to binary data after stitching in the request body, the stitching process must be strictly in accordance with the format of splicing, otherwise, the upload fails; as shown, all empty lines, line breaks are \r\n represented, the space between the end of the parameter and \r\n the spacing between the argument and the actual non-existent, Just for the convenience of reading.
3. Set non-file parameters:
?重要: Non-file parameters and file parameters in the setting of the Content-Disposition difference, file parameters: name used file , indicating that this is a file, and also need to pass to the server filename (that is, the file is uploaded to the server after the name); Non-file parameters: simply set name , and the parameters corresponding to the Keyrepresents the parameter and then stitching the value of the parameter in the form of binary data in the position of the parameter value.
2, the File upload function realizes:
?重要: File upload, the data that needs to be passed can be very large, so the simple request cannot be used GET and the POST request is completed. Also, the file upload needs to set the request header Content-Type information, so you need to use a mutable request object (i.e.: NSMutableURLRequest ), use KVC the method to set the property, tell the server this is a file upload operation.
2-1. Create an upload request operation:
1.-(void) upload{
2.//1. Create URL
3. Nsurl *url = [Nsurl urlwithstring:@ "Http://120.25.226.186:32812/upload"];
4.
5.//2. Create a mutable Request object
6. Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
7.
8.//3. Set the request method to post
9. Request. HttpMethod = @ "POST";
10.
11.//4. Set the request header information to tell the server this is a file upload request
12.//In this place from error, should be form; It took me 1 hours to get this one wrong.
13.//[Request setvalue:[nsstring stringwithformat:@ "multipart/from-data; boundary=%@", Kboundary] forhttpheaderfield:@ "Content-type"];
[Request setvalue:[nsstring stringwithformat:@ "multipart/form-data; boundary=%@", Kboundary] ForHTTPHeaderField: @ "Content-type"];
15.
16.//4. Get default configuration information
Nsurlsessionconfiguration *configuration = [Nsurlsessionconfiguration defaultsessionconfiguration];
18.
19.//5. To create a Session object
Nsurlsession *session = [nsurlsession sessionwithconfiguration:configuration delegate:self delegateQueue:[ Nsoperationqueue Mainqueue]];
21st.
22.//6. To create an upload task object using a Session object
[[Session Uploadtaskwithrequest:request Fromdata:[self Bodydata] completionhandler:^ (NSData * _Nullable data, NSURL Response * _nullable Response, Nserror * _nullable error) {
24.
NSLog (@ "%@", [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]);
.}] "Resume";
27.}
?重要: 1, file upload usually use a member of the NSURLSessionTask family NSURLSessionUploadTask , after setting the request method and the request header information; Use the session object to create a file upload session task, and invoke the resume method to open the File Upload task operation.
?重要: 2, in the use of NSURLSessionUploadTask file upload, you can also set the agent of the session object, in order to listen to the progress of the file upload operation, the agent must abide by the " NSURLSessionDataDelegate protocol." Common Proxy methods:
1.
2.#pragma mark NSURLSessionDataDelegate
3.
4.//bytesSent 本次上传的文件数据大小
5.//totalBytesSent 已经上传的文件数据的总大小
6.//totalBytesExpectedToSend 文件的总大小
7.-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
8.{
9. NSLog(@"%f",1.0 * totalBytesSent / totalBytesExpectedToSend);
10.}
2-2, stitching file parameters and non-file parameters:
1./**
2. * Splicing request body data, tested without errors
3. */
4.-(Nsmutabledata *) getdata{
5.//MARK:-File parameters
6.//1. Create data
7. Nsmutabledata *filedata = [Nsmutabledata data];
8.
9.//2. Splicing--Split line
NSString *str = [NSString stringwithformat:@ "--%@", kboundary];
[FileData Appenddata:[str datausingencoding:nsutf8stringencoding]];
12.
[FileData Appenddata:newline];
14.
15.//4. Stitching Content-disposition
str = [NSString stringwithformat:@ "content-disposition:form-data; name=\" file\ "; filename=\" Snip20161128_2.png\ " "];
[FileData Appenddata:[str datausingencoding:nsutf8stringencoding]];
18.
[FileData Appenddata:newline];
20.
21.//5. Stitching content-type, File MimeType format: Large type/small type
str = [NSString stringwithformat:@ "Content-type:image/png"];
[FileData Appenddata:[str datausingencoding:nsutf8stringencoding]];
24.
[FileData Appenddata:newline];
26.
27.//6. Splicing blank lines, to ensure that in any environment can be correctly wrapped, so use: \ r \ n
28.
[FileData Appenddata:newline];
30.
31.//7. Stitching file Data
[FileData appenddata:[nsdata datawithcontentsoffile:@ "/users/hehuafeng/desktop/snip20161128_2.png"];
33.
34.//8. Wrap end of File data
[FileData Appenddata:newline];
36.
PNs.//MARK:-Non-file parameters
38.//1. Splicing Split Line
NSString str = [stringwithformat:@ "--%@", kboundary];
[FileData Appenddata:[str datausingencoding:nsutf8stringencoding]];
41.
[FileData Appenddata:newline];
43.
44.//2. Stitching Content-disposition
str = [NSString stringwithformat:@ "content-disposition:form-data; name=\" username\ ""];
[FileData Appenddata:[str datausingencoding:nsutf8stringencoding]];
47.
[FileData Appenddata:newline];
[FileData Appenddata:newline];
50.
51.//4. Stitching parameter values
NSString str = [stringwithformat:@ "hahaha"];
[FileData Appenddata:[str datausingencoding:nsutf8stringencoding]];
54.
[FileData Appenddata:newline];
56.
//Mark:-Stitching parameter end tag
. str = [NSString stringwithformat:@ "--%@--", kboundary];
[FileData Appenddata:[str datausingencoding:nsutf8stringencoding]];
60.
//MARK:-Returns the finished data
. return fileData;
63.}
?重要: 1, splicing files non-file parameters, must be strictly in accordance with the format of splicing; otherwise, you will not be able to upload files.
?重要: 2, file parameters and non-file parameter stitching steps --分割线 : 换行(\r\n) 文件参数的:Content-Dispositio 换行(\r\n) 文件参数的:Content-Type 换行(\r\n) 空一行(\r\n) 二进制形式文件参数值 换行(\r\n) ----- --分割线 换行(\r\n) 非文件的:Content-Disposition 换行(\r\n) 空一行(\r\n) 二进制形式非文件参数值 换行(\r\n)--分割线--(即:结束标记)
2-3, the file upload using the macro:
1.// 分割线, 为确保分析按正常换行; 所以, 使用\r\n
2.#define kBoundary @"----WebKitFormBoundarybH2OxPYq4hkfGHY6"
3.#define newLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
iOS Core notes-network programming-File Upload