创建一个带有jpg的纯HTTPPUT多部分请求



我正在手动创建一个HTTP PUT请求。我有以下格式的

POST http://server.com/id/55/push HTTP/1.0
Content-type: multipart/form-data, boundary=AaB03x
Content-Length: 168
--AaB03x
Content-Disposition: form-data; name="image"; filename="small.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
<file content>
--AaB03x--

我的问题是,我应该如何填写";文件内容";地区如果我用TexMate或cat命令行应用程序打开jpeg,并粘贴ASCII输出,则请求不起作用。

更新

我使用的是微处理器,我不能使用C或高级语言,我需要手动完成原始请求。我需要用空格分隔从文件中读取的每个二进制字节吗?

如果将jpg保存到服务器端的文件中,是否必须将二进制流转换为ASCII?

我用一个简单的php conde:从硬盘上读取JPG的二进制代码

$filename = "pic.jpg";
$handle = fopen($filename, "rb");
$fsize = filesize($filename);
$contents = fread($handle, filesize($filename));
fclose($handle);
//echo $contents;
for($i = 0; $i < $fsize; $i++)
{ 
  // get the current ASCII character representation of the current byte
   $asciiCharacter = $contents[$i];
   // get the base 10 value of the current characer
   $base10value = ord($asciiCharacter);
   // now convert that byte from base 10 to base 2 (i.e 01001010...)
   $base2representation = base_convert($base10value, 10, 2);
   // print the 0s and 1s
   echo($base2representation);
}

通过这个代码,我得到了一个1和0的流。我可以将包括101010101的字符串的它发送到标记"的位置;文件内容";我的手动http请求是,但在服务器端,我无法可视化JPG。。。?我应该再次将其转换为ASCII吗?

解决方案

好吧,解决方案非常简单,我只是将ASCII代码转储到标签"中;文件内容";http请求的。尽管我使用的是微控制器,但我还是用PHP打开了一个套接字并进行了测试。解决方案是从文件中读取ASCII,而不是直接将ASCII粘贴到代码中。

这里有一个解决方案的工作示例:

<?php
//We read the file from the hard drive
$filename = "pic.jpg";
$handle = fopen($filename, "rb");
$fsize = filesize($filename);
$contents = fread($handle, filesize($filename));
fclose($handle);
$mesage = $contents;
//A trick to calculate the length of the HTTP body
$len = strlen('--AaB03x
Content-Disposition: form-data; name="image"; filename="small.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
'.$mesage.'
--AaB03x--');

//We create the HTTP request
$out = "POST /temp/test.php HTTP/1.0rn";
$out .= "Content-type: multipart/form-data boundary=AaB03xrn";
$out .= "Content-Length: $lenrnrn";
$out .= "--AaB03xrn";
$out .= "Content-Disposition: form-data; name="image"; filename="small.jpg"rn";
$out .= "Content-Type: image/jpegrn";
$out .= "Content-Transfer-Encoding: binaryrnrn";
$out .= "$mesagern";
$out .= "--AaB03x--rnrn";
//Open the socket 
$fp = fsockopen("127.0.0.1", 8888, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />n";
} else {
    
    //we send the message thought the opened socket
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
//Visualize the query sent
echo nl2br($out);
?>

在实际实现中,我将简单地直接从微控制器的内存中读取,就像我在php 中所做的那样

您输入错误的最后一个边界,它应该是:

--AaB03x--

您需要有一个输出连接的OutputStream,并使用此Stream写入从文件中读取的所有字节。

如果您使用C#。您可以检查:在c#中使用HTTPPOST发送文件

对于Java:

  • URLConnection上的图像写入
  • 如何通过文件上传将数据发送到服务器
  • HttpURLConnection POST,conn.getOutputStream()引发异常

最新更新