Steps for uploading files
1. Set the request header
* Purpose: To tell the server that the contents of the request body are not normal parameters, but include the file parameters
setValue:@"multipart/form-data; boundary=maljob"forHTTPHeaderField:@"Content-Type"];
2. Set the request body
* Function: Store parameters (file parameters and non-file parameters)
1> Non-file parameters
[body appendData:MalJobEncode(@"--maljob\r\n")];[body appendData:MalJobEncode(@"Content-Disposition: form-data; name=\"username\"\r\n")];
[body appendData:MalJobEncode(@"\r\n")];[body appendData:MalJobEncode(@"张三")];[body appendData:MalJobEncode(@"\r\n")];
2> file Parameters
[ body AppendData: Maljobencode (@ "--heima\r \n ") " ; [ body Appenddata:maljobencode (@ "CONTENT-DISPOSITION:FORM-DATA; Name=\ " file\" ; Filename=\ " test123.png\" \r \n ") ; [ body Appenddata:maljobencode (@ "Content-type:image/png \r \n ") ;
[body appendData:MalJobEncode(@"\r\n")];[body appendData:imageData];[body appendData:MalJobEncode(@"\r\n")];
3> end tag: marker for end of parameter
[bodyappendData:MalJobEncode(@"--maljob--\r\n")];
MimeType of the file
1. Baidu Search
2. Find an XML file below the server
apache-tomcat-6.0.41\conf\web.xml
3. When loading a file, get it via reponse
- (NSString *)MIMEType:(NSURL *)url{ // 1.创建一个请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 2.发送请求(返回响应) nil; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; // 3.获得MIMEType return response.MIMEType;}
File Upload wrapper tool class
@interface UploadTool : NSObject/** * 根据文件路径获取文件的MIMEType * * @param url 文件路径 * * @return 文件MIMEType */- (NSString *)MIMEType:(NSURL *)url;/** * 根据文件名、MIMEType、二进制文件、其他的参数上传文件 * * @param filename 文件名 * @param mimeType MIMEType * @param fileData 二进制文件 * @param params 非文件的其他详细参数 */- (void)upload:(NSString *)filename mimeType:(NSString *)mimeType fileData:(NSData *)fileData params:(NSDictionary *)params;@end
#define Mjfileboundary @ "Maljob"#define Mjnewline @ "\ r \ n"#define MJENCODE (str) [str datausingencoding:nsutf8stringencoding]#import "UploadTool.h" @implementation uploadtool - (NSString*) MIMEType: (Nsurl*) url{//1. Create a request nsurlrequest*request = [nsurlrequestRequestwithurl:url];//2. Send request (return response)Nsurlresponse *response =Nil; [nsurlconnectionSendsynchronousrequest:request Returningresponse:&response Error:Nil];//3. Get MimeType returnResponse. MIMEType;} - (void) Upload: (NSString*) filename MimeType: (NSString*) MimeType FileData: (NSData *) FileData params: (nsdictionary*) params{//1. Request Path Nsurl*url = [Nsurlurlwithstring:@"Http://218.83.161.124:8080/job/upload"];//2. Create a POST requestNsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; Request. HttpMethod= @"POST";//3. Set the request bodyNsmutabledata *body = [Nsmutabledata data];//3.1. File Parameters[Body Appenddata:mjencode (@"--")]; [Body Appenddata:mjencode (mjfileboundary)]; [Body Appenddata:mjencode (mjnewline)];NSString*disposition = [NSStringstringwithformat:@"Content-disposition:form-data; Name=\ "File\"; Filename=\ "%@\" ", filename]; [Body Appenddata:mjencode (disposition)]; [Body Appenddata:mjencode (mjnewline)];NSString*type = [NSStringstringwithformat:@"Content-type:%@", MimeType]; [Body Appenddata:mjencode (type)]; [Body Appenddata:mjencode (mjnewline)]; [Body Appenddata:mjencode (mjnewline)]; [Body appenddata:filedata]; [Body Appenddata:mjencode (mjnewline)];//3.2. Non-file parameters[Params enumeratekeysandobjectsusingblock:^ (IDKeyIDObjBOOL*stop) {[Body Appenddata:mjencode (@"--")]; [Body Appenddata:mjencode (mjfileboundary)]; [Body Appenddata:mjencode (mjnewline)];NSString*disposition = [NSStringstringwithformat:@"Content-disposition:form-data; Name=\ "%@\" ", key]; [Body Appenddata:mjencode (disposition)]; [Body Appenddata:mjencode (mjnewline)]; [Body Appenddata:mjencode (mjnewline)]; [Body appenddata:mjencode ([obj description]); [Body Appenddata:mjencode (mjnewline)]; }];//3.3. End tag[Body Appenddata:mjencode (@"--")]; [Body Appenddata:mjencode (mjfileboundary)]; [Body Appenddata:mjencode (@"--")]; [Body Appenddata:mjencode (mjnewline)]; Request. Httpbody= Body;//4. Set the request header (tell the server this time to you is the file data, tell the server is now sending a file upload request) NSString*contenttype = [NSStringstringwithformat:@"Multipart/form-data; boundary=%@ ", Mjfileboundary]; [Request Setvalue:contenttype forhttpheaderfield:@"Content-type"];//5. Send Request[nsurlconnectionSendasynchronousrequest:request Queue:[nsoperationqueue Mainqueue] completionhandler:^ (NSURLResponse *response, NSData *data,Nserror*connectionerror) {nsdictionary*dict = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves Error:Nil]; Maljoblog (@"%@", dict); }];} - (void) upload{//non-file other detailed parameters nsdictionary*params = @{@"": @"", @"": @"", };Nsurl*url = [[NSBundleMainbundle] urlforresource:@"FileName"withextension:@"TXT"]; NSData *data = [NSData Datawithcontentsofurl:url];NSString*mimetype = [ SelfMimetype:url]; [ Selfupload:@"Filename.txt"Mimetype:mimetype filedata:data params:params];}
iOS Development-Package file Upload Tool class