To upload a file using http post, we need to pass the file resource type to the server, so that the server can determine whether the file is a picture, audio, or video. This article is about using Objective C under the iOS project to get the MIME Type (Content Type) of a file based on the extension type of the file name.
Example
RequiresMobileCoreServices.framework
. Add the framework toBuild Phases -> Link Binary With Libraries
, and include the MobileCoreServices framework.
#import <MobileCoreServices/MobileCoreServices.h>
- (NSString *)getMimeType:(NSString *)fileExtension{
NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL);
NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
return mimeType;
}
Use it
NSString *path = @"/home/test.png";
NSString *fileExtension = [path pathExtension];
NSString *contentType = [self getMimeType:fileExtension];
NSLog(@"%@", contentType);
Attention
What you get with this method is not the true MIME-Type of the file. For example, a picture is png and the MIME Type isimage/png
. If the extension of this picture is changed to jpg, you will get image/jpeg
.
To upload a file using http post, we need to pass the file resource type to the server, so that the server can determine whether the file is a picture, audio, or video. This article is about using Objective C under the iOS project to get the MIME Type (Content Type) of a file based on the extension type of the file name.
Example
Requires
MobileCoreServices.framework
. Add the framework toBuild Phases -> Link Binary With Libraries
, and include the MobileCoreServices framework.Use it
Attention
What you get with this method is not the true MIME-Type of the file. For example, a picture is png and the MIME Type is
image/png
. If the extension of this picture is changed to jpg, you will getimage/jpeg
.