首页 \ 问答 \ cURL以NSMutableURLRequest格式上传照片命令(cURL upload photo command in NSMutableURLRequest format)

cURL以NSMutableURLRequest格式上传照片命令(cURL upload photo command in NSMutableURLRequest format)

我知道这看起来可能与手头的问题有关,但是,这是我试图避免可怕的上传包含大量(而且过时)数量依赖的可可豆荚的上传使用,以便上传文件(然后下载它)在以后的日子)。

我正在努力翻译cURL命令中的'-F'选项。 我知道他们指定HTTP多部分POST数据,但是将其转换为附加图片文件的NSMutableData很困难。 我一直收到403状态代码。

cURL命令是:

curl -F "UPLOADCARE_PUB_KEY=e84a031b3da1g560d56d"  \
-F "UPLOADCARE_STORE=1"  \
-F "file=@aaronmillman.jpg" https://upload.uploadcare.com/base/

我目前的尝试是:

NSMutableData *body = [NSMutableData data];
NSData *imageData = UIImageJPEGRepresentation(image, 0.6);
if (imageData) {
    [body appendData:[@"UPLOADCARE_PUB_KEY=e84a031b3da1g560d56d" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"UPLOADCARE_STORE=1" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"file="] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
}

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

NSURL *url = [NSURL URLWithString:baseUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = imageData;
NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"%@",response);
}];
[uploadTask resume];

我对NSMutableData做错了什么?

第二个相关问题是:是否值得使用Objective-C lib curl包装器?


I know this may seem specific to the issue at hand, however, this is me trying to avoid the horrible UploadCare usage of cocoa pods which contains a significant (and rather outdated) amount of dependencies, to JUST upload a file (and subsequently download it at a later date).

I'm struggling to translate the '-F' options in the cURL command. I understand that they specify HTTP multipart POST data, but converting this into NSMutableData with the picture file attached is difficult. I keep receiving a 403 status code.

The cURL command is:

curl -F "UPLOADCARE_PUB_KEY=e84a031b3da1g560d56d"  \
-F "UPLOADCARE_STORE=1"  \
-F "file=@aaronmillman.jpg" https://upload.uploadcare.com/base/

My current attempt is:

NSMutableData *body = [NSMutableData data];
NSData *imageData = UIImageJPEGRepresentation(image, 0.6);
if (imageData) {
    [body appendData:[@"UPLOADCARE_PUB_KEY=e84a031b3da1g560d56d" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"UPLOADCARE_STORE=1" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"file="] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
}

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

NSURL *url = [NSURL URLWithString:baseUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = imageData;
NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"%@",response);
}];
[uploadTask resume];

What am I doing wrong with the NSMutableData?

A second, and related question is: Is it worth using an objective-C lib curl wrapper at all?


原文:https://stackoverflow.com/questions/25597370
更新时间:2023-03-16 11:03

最满意答案

光滑3.0的包结构已更改 。 您需要使用slick.codegen.SourceCodeGenerator而不是scala.slick.codegen.SourceCodeGenerator


Got this running :) Apart from changing the version numbers (see above) I had to:

  • remove the "scala." prefix from slick package names in Build.scala (thanks again, Alex)
  • change all "create table" to "create table if not exists" in create.sql
  • rewrite Example.scala:

    object Example extends App {
      // connection info for a pre-populated throw-away, in-memory db for this demo, which is freshly initialized on every run
      val url = "jdbc:h2:mem:test;INIT=runscript from 'src/main/sql/create.sql'"
      val db = Database.forURL(url, driver = "org.h2.Driver")
    
      // Using generated code. Our Build.sbt makes sure they are generated before compilation.
      val query = Companies.join(Computers).on(_.id === _.manufacturerId).map{ case (co,cp) => (co.name, cp.name) }
      val future = db.run(query.result)
    
      future onSuccess {  
        case result => println(result.groupBy{ case (co,cp) => co }
                                     .mapValues(_.map{ case (co,cp) => cp })
                                     .mkString("\n")
                              )
      }
      future onFailure {
        case t => println("Got an error: " + t.getMessage)
      }
      Thread.sleep(1000)    
    }
    

相关问答

更多
  • 我得到了这个例子的工作: Tables._和Tables.profile.api._只需要在类中导入隐式Database 。 import slick.jdbc.JdbcBackend class Test(s: String)(implicit db: Database) { import Tables._ import Tables.profile.api._ def exec[T](action: DBIO[T])(implicit db: Database): T = ...
  • 我最终进一步定制了slick-codegen 。 首先,我会回答自己的问题,然后我会发布我的解决方案。 问题的答案 案例类可以取消22个参数限制,但不适用于元组。 而且slick-codegen也产生了一些元组,当我问这个问题时我并没有完全意识到。 不相关,请参阅答案1.(如果元组的权限限制也取消了,这可能会变得相关。) 我选择不进一步调查,所以这个问题目前还没有答案。 这是我最终采取的方法。 解决方案:生成的代码 所以,我最终为超过22列的表生成“普通”类。 让我举一个我现在产生的例子。 (发生器代码如下 ...
  • OP表示“也接受其他建议”。 他可能会考虑我们的DMS软件再造工具包及其C前端 。 虽然展示由此产生的C AST非常容易,但是使用相同的C前端(ObjectiveC是C的方言)显示由DMS产生的ObjectiveC AST [已经在SO]更容易。 请参阅https://stackoverflow.com/a/10749970/120163 DMS也可以生成与此等效的XML。 我们不建议将树导出为文本,因为实际代码的真实树只是巨大的,并且在我们的经验中作为文本或XML对象操作很差。 人们通常需要解析之外的机器 ...
  • 更新当前安装的pod update版本的唯一方法是运行pod update 。 如果不这样做,所有当前版本信息都存储在Podfile.lock ,并确保安装之间的版本相同。 如果要添加这些文件,此文件也是查找这些版本的最佳位置。 在你的Podfile.lock你会看到一个这样的列表: PODS: - EasyMapping (0.6.3) - Expecta (0.3.1) - OCMock (3.1.1) - OHHTTPStubs (3.1.6): - OHHTTPStubs/C ...
  • 只需抓住Qt Creator独立包并在某处安装即可。 确保保留用户设置,因为Creator会升级这些设置,之后您的旧版本将无法读取所有这些设置。 您可以复制现有设置的(%APPDATA%/ ... / QtProject或〜/ .config / QtProject IIRC),也可以使用-settingspath / some / dir启动新创建者。 Just grab the Qt Creator stand-alone package and install that somewhere. Do m ...
  • 在project/build.sbt声明对Typesafe配置的依赖: libraryDependencies += "com.typesafe" % "config" % "1.3.1" 并在build.sbt定义一个包含配置文件的build.sbt : lazy val myConf = settingKey[Config]("The application properties") myConf := { ConfigFactory.parseFile(new File("src/main ...
  • 不要这样做。 Slick的核心优势之一来自于撰写查询。 虽然你想要的是你可能会打破这种力量。 而是写查询! implicit class PersonExtension(q: Query[Person,PersonRow]){ def dogs = q.join(Dog).on(_.id === _.ownerId).map(_._2) } implicit class DogExtension(q: Query[Person,PersonRow]){ def owner = q.join(Pers ...
  • 光滑3.0的包结构已更改 。 您需要使用slick.codegen.SourceCodeGenerator而不是scala.slick.codegen.SourceCodeGenerator Got this running :) Apart from changing the version numbers (see above) I had to: remove the "scala." prefix from slick package names in Build.scala (thanks aga ...
  • 您正在尝试在项目目录中编译。 将目录更改为/adongre1/external/scala-slick/slick/然后运行sbt compile 。 You are trying to compile in the project directory. Change directories to /adongre1/external/scala-slick/slick/ then run sbt compile.
  • 这是由IntelliJ无法识别生成的代码引起的,可以尝试将target/scala-2.11/src_managed/slick/ this标记为Sources Root 。 喜欢: This is caused by IntelliJ can't recognize the generated code, you can try to mark target/scala-2.11/src_managed/slick/ this as Sources Root. like:

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)