代码之家  ›  专栏  ›  技术社区  ›  wfgeo

在curl[duplicate]中重新创建来自Django Rest框架测试的基于文件的POST请求

  •  0
  • wfgeo  · 技术社区  · 5 年前

    我想使用cURL不仅可以在HTTPPOST中发送数据参数,还可以上传具有特定表单名称的文件。我该怎么做呢?

    HTTP Post参数:

    userid=12345 filecomment=这是一个图像文件

    HTTP文件上传: 文件位置=/home/user1/Desktop/test。jpg file=image的表单名(与PHP端的$_文件['image']相对应)

    我对cURL命令的一部分进行了如下计算:

    curl -d "userid=1&filecomment=This is an image file" --data-binary @"/home/user1/Desktop/test.jpg" localhost/uploader.php
    

    我遇到的问题如下:

    Notice: Undefined index: image in /var/www/uploader.php
    

    问题是我正在使用$_FILES['image']来提取PHP脚本中的文件。

    如何相应地调整卷曲命令?

    0 回复  |  直到 5 年前
        1
  •  760
  •   jwfearn    11 年前

    你需要使用 -F 选项:
    -F/--form <name=content> Specify HTTP multipart POST data (H)

    试试这个:

    curl \
      -F "userid=1" \
      -F "filecomment=This is an image file" \
      -F "image=@/home/user1/Desktop/test.jpg" \
      localhost/uploader.php
    
        2
  •  124
  •   r1ckr    8 年前

    将用户id捕获为路径变量(推荐):

    curl -i -X POST -H "Content-Type: multipart/form-data" 
    -F "data=@test.mp3" http://mysuperserver/media/1234/upload/
    

    捕获用户id作为表单的一部分:

    curl -i -X POST -H "Content-Type: multipart/form-data" 
    -F "data=@test.mp3;userid=1234" http://mysuperserver/media/upload/
    

    或者:

    curl -i -X POST -H "Content-Type: multipart/form-data" 
    -F "data=@test.mp3" -F "userid=1234" http://mysuperserver/media/upload/
    
        3
  •  22
  •   halfer Jatin Pandey    11 年前

    这是我的解决方案,我已经读了很多帖子,它们真的很有帮助。最后,我用cURL和PHP为小文件编写了一些代码,我认为它们非常有用。

    public function postFile()
    {    
            $file_url = "test.txt";  //here is the file route, in this case is on same directory but you can set URL too like "http://examplewebsite.com/test.txt"
            $eol = "\r\n"; //default line-break for mime type
            $BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
            $BODY=""; //init my curl body
            $BODY.= '--'.$BOUNDARY. $eol; //start param header
            $BODY .= 'Content-Disposition: form-data; name="sometext"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
            $BODY .= "Some Data" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
            $BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
            $BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
            $BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
            $BODY.= 'Content-Transfer-Encoding: base64' . $eol . $eol; // we put the last Content and 2 $eol,
            $BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
            $BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
    
    
    
            $ch = curl_init(); //init curl
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                             'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
                             ,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
                        );
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
            curl_setopt($ch, CURLOPT_URL, "api.endpoint.post"); //setting our api post url
            curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
            curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); navigate the endpoint
            curl_setopt($ch, CURLOPT_POST, true); //set as post
            curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY 
    
    
            $response = curl_exec($ch); // start curl navigation
    
         print_r($response); //print response
    
    }
    

    有了这些,我们应该可以在“api.endpoint.post”上看到下面的变量。你可以很容易地用这个脚本进行测试,你应该会收到这个函数的调试结果 postFile() 在最后一排。

    print_r($response); //print response
    
    public function getPostFile()
    {
    
        echo "\n\n_SERVER\n";
        echo "<pre>";
        print_r($_SERVER['HTTP_X_PARAM_TOKEN']);
        echo "/<pre>";
        echo "_POST\n";
        echo "<pre>";
        print_r($_POST['sometext']);
        echo "/<pre>";
        echo "_FILES\n";
        echo "<pre>";
        print_r($_FILEST['somefile']);
        echo "/<pre>";
    }
    

    它应该可以很好地工作,它们可能是更好的解决方案,但这很有效,对于理解Boundary和multipart/from data mime在PHP和cURL库上的工作方式非常有帮助。

        4
  •  19
  •   KARTHIKEYAN.A    8 年前

    如果您正在上载二进制文件,如csv,请使用以下格式上载文件

    curl -X POST \
        'http://localhost:8080/workers' \
        -H 'authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyIsInR5cGUiOiJhY2Nlc3MifQ.eyJ1c2VySWQiOjEsImFjY291bnRJZCI6MSwiaWF0IjoxNTExMzMwMzg5LCJleHAiOjE1MTM5MjIzODksImF1ZCI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20iLCJpc3MiOiJmZWF0aGVycyIsInN1YiI6ImFub255bW91cyJ9.HWk7qJ0uK6SEi8qSeeB6-TGslDlZOTpG51U6kVi8nYc' \
        -H 'content-type: application/x-www-form-urlencoded' \
        --data-binary '@/home/limitless/Downloads/iRoute Masters - Workers.csv'
    
        5
  •  10
  •   Evandro Pomatti    6 年前

    经过多次尝试,这个命令对我有效:

    curl -v -F filename=image.jpg -F upload=@image.jpg http://localhost:8080/api/upload
    
        6
  •  5
  •   shonky linux user    7 年前

    导致我出现在这里的问题是一个基本的用户错误-我没有包括 @ 在文件路径上签名,这样curl就发布了文件的路径/名称,而不是内容。这个 Content-Length 因此,考虑到测试文件的长度,该值是8,而不是我期望看到的479。

    这个 内容长度 当curl读取并发布文件时,将自动计算头。

    curl -i -H "Content-Type: application/xml" --data "@test.xml" -v -X POST https://<url>/<uri/

    ... <内容长度:479 ...

    在这里发布这篇文章是为了将来帮助其他新手。

        7
  •  4
  •   Gîanfranco P.    8 年前

    作为替代 curl ,你可以使用 HTTPie 这是一个CLI,类似于人类的卷曲工具。

    1. 安装说明: https://github.com/jakubroztocil/httpie#installation

    2. 然后,运行:

      http -f POST http://localhost:4040/api/users username=johnsnow photo@images/avatar.jpg
      
      HTTP/1.1 200 OK
      Access-Control-Expose-Headers: X-Frontend
      Cache-control: no-store
      Connection: keep-alive
      Content-Encoding: gzip
      Content-Length: 89
      Content-Type: text/html; charset=windows-1251
      Date: Tue, 26 Jun 2018 11:11:55 GMT
      Pragma: no-cache
      Server: Apache
      Vary: Accept-Encoding
      X-Frontend: front623311
      
      ...
      
        8
  •  1
  •   Vladimir Panteleev    10 年前

    下面是如何使用 bash :

    #!/bin/bash
    set -eu
    
    f="$1"
    f=${f//\\/\\\\}
    f=${f//\"/\\\"}
    f=${f//;/\\;}
    
    curl --silent --form "uploaded=@\"$f\"" "$2"
    
        9
  •  1
  •   Shravan Hebbar    6 年前

    我用这个命令完成了 curl -F 'filename=@/home/yourhomedirextory/file.txt' http://yourserver/upload

        10
  •  0
  •   he shouyong    5 年前
    cat test.txt 
    

    文件测试。文本内容。

    curl -v -F "hello=word" -F "file=@test.txt" https://httpbin.org/post
    
    > POST /post HTTP/2
    > Host: httpbin.org
    > user-agent: curl/7.68.0
    > accept: */*
    > content-length: 307
    > content-type: multipart/form-data; boundary=------------------------78a9f655d8c87a53
    > 
    * Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
    * We are completely uploaded and fine
    < HTTP/2 200 
    < date: Mon, 15 Nov 2021 06:18:47 GMT
    < content-type: application/json
    < content-length: 510
    < server: gunicorn/19.9.0
    < access-control-allow-origin: *
    < access-control-allow-credentials: true
    < 
    {
      "args": {}, 
      "data": "", 
      "files": {
        "file": "file test.txt content.\n"
      }, 
      "form": {
        "hello": "word"
      }, 
      "headers": {
        "Accept": "*/*", 
        "Content-Length": "307", 
        "Content-Type": "multipart/form-data; boundary=------------------------78a9f655d8c87a53", 
        "Host": "httpbin.org", 
        "User-Agent": "curl/7.68.0", 
        "X-Amzn-Trace-Id": "Root=1-6191fbc7-6c68fead194d943d07148860"
      }, 
      "json": null, 
      "origin": "43.129.xx.xxx", 
      "url": "https://httpbin.org/post"
    }
    
    推荐文章