zoukankan      html  css  js  c++  java
  • iOS开发之网络编程--获取文件的MIMEType

    前言:有时候我们需要获取文件的MIMEType的信息,下面就介绍关于获取MIMEType的方法。

    1、直接百度搜索关键字"MIMEType",你会找到,然后查吧:

    2、用代码获取文件的MIMEType信息:

     1 #import "GetMIMEType.h"
     2 
     3 #import <MobileCoreServices/MobileCoreServices.h>
     4 
     5 @implementation GetMIMEType
     6 
     7 #pragma mark - 类方法
     8 + (NSString*)getMIMETypeURLRequestAtFilePath:(NSString*)path{
     9     return [[[GetMIMEType alloc] init] getMIMETypeURLRequestAtPath:path];
    10 }
    11 
    12 + (NSString *)getMIMETypeWithCAPIAtFilePath:(NSString *)path{
    13     return [[[GetMIMEType alloc] init] getMIMETypeWithCAPIAtFilePath:path];
    14 }
    15 #pragma mark - 对象方法
    16 //向该文件发送请求,根据请求头拿到该文件的MIMEType
    17 -(NSString *)getMIMETypeURLRequestAtPath:(NSString*)path
    18 {
    19     //1.确定请求路径
    20     NSURL *url = [NSURL fileURLWithPath:path];
    21     
    22     //2.创建可变的请求对象
    23     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    24     
    25     //3.发送请求
    26     NSHTTPURLResponse *response = nil;
    27     [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    28     
    29     NSString *mimeType = response.MIMEType;
    30     return mimeType;
    31 }
    32 
    33 //调用C语言的API来获得文件的MIMEType ,只能获取本地文件哦,无法获取网络请求来的文件
    34 -(NSString *)getMIMETypeWithCAPIAtFilePath:(NSString *)path
    35 {
    36     if (![[[NSFileManager alloc] init] fileExistsAtPath:path]) {
    37         return nil;
    38     }
    39     
    40     CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);
    41     CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    42     CFRelease(UTI);
    43     if (!MIMEType) {
    44         return @"application/octet-stream";
    45     }
    46     return (__bridge NSString *)(MIMEType)
    47     ;
    48 }
    49 
    50 @end

    运行:

    github源码下载:https://github.com/HeYang123456789/GetMIMEType

  • 相关阅读:
    索引
    mysql事务
    centos 7 gitlab安装服务器
    内网穿透工具 frp使用
    eslint配置
    nodejs连接mongodb(密码)
    插入排序
    直接插入排序
    koa中 log4js使用
    JS中的prototype、__proto__与constructor(图解)
  • 原文地址:https://www.cnblogs.com/goodboy-heyang/p/5193741.html
Copyright © 2011-2022 走看看