上传Image MultiPart Form HTTPWebRequest - 将图像数据转换为字符串?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传Image MultiPart Form HTTPWebRequest - 将图像数据转换为字符串?相关的知识,希望对你有一定的参考价值。

我正在尝试使用HTTPWebRequest上传多部分表单并且一切正常,直到我添加了要上传的图像,主要是我尝试执行与浏览器完全相同的请求,如下所示:

-----------------------------41184676334
Content-Disposition: form-data; name="file"; filename="guitar tape.jpg"
Content-Type: image/jpeg

IMAGEDATAHERE
-----------------------------41184676334
Content-Disposition: form-data; name="save"

save
-----------------------------41184676334--

我迷失在如何格式化/读取图像以将其设置为我在下面的请求中:

            Dim boundary As String = "-----------------------------" & DateTime.Now.Ticks.ToString("x")
        Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://www.mysite.com/upload.php"), HttpWebRequest)
        req.Method = "POST"
        req.ContentType = "multipart/form-data; boundary=" & "---------------------------" & DateTime.Now.Ticks.ToString("x")
        req.KeepAlive = False
        Dim builder As New StringBuilder()
        builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""variable1""" & vbCrLf & vbCrLf & "1" & vbCrLf)
        builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""file""; filename=""" & FileName & """" & vbCrLf)
        builder.Append("Content-Type: application/octet-stream")
        builder.Append(vbCrLf & vbCrLf)
        ' Add Photo Here
        If UpdateImage = True Then
            ' Load Image
            Dim ImageData As System.Drawing.Image
            Dim fs As New System.IO.FileStream(ImagePath, System.IO.FileMode.Open)
            ImageData = Image.FromStream(fs)
            fs.Close()
            ' Add Image To Header
            builder.Append(ImageData)
            builder.Append(vbCrLf)
        Else
            builder.Append(vbCrLf)
        End If
        builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""save""" & vbCrLf & vbCrLf & "save")
        ' Footer Bytes
        Dim close As Byte() = Encoding.UTF8.GetBytes("--")
        Dim postHeader As String = builder.ToString()
        Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(postHeader)
        Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(vbCrLf & boundary & "--" & vbCrLf)
        Dim length As Long = postHeaderBytes.Length + boundaryBytes.Length
        req.ContentLength = length
        Dim requestStream As Stream = req.GetRequestStream()
        Dim fulllength As Integer = postHeaderBytes.Length + boundaryBytes.Length
        ' Write out our post header
        requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
        ' Write out the trailing boundary
        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
        Dim responce As WebResponse
        responce = req.GetResponse()
        requestStream.Close()
        Dim s As Stream = responce.GetResponseStream()
        Dim sr As New StreamReader(s)
        Dim Content As String = sr.ReadToEnd()

目前它只是将“System.Drawing.Bitmap”作为图像数据发布,但我不知道如何获得与此类似的图像的相同原始数据:

    J©õݨe‚Lnž¿Ëã/ǧúÐ5ý¼C÷Cý>ß’t;fm—=Äw:�/E±ËÙÏ$á@%Pc>×    Šgw.²Ab“:ÅÓù:ϯÌh6à€Z§Ó‚g£®hÚD6¨Ø^Ú2ô`ä¨L�YÆÄÅCX#I“ÈÌãj¦L˜•’|¥�Eb¡ëQ–¤Ú, 3UzL  öÔoj4�•±’u«c¼#„oÕ`îF>·o—ŠûÅ«ÎÑ™¶Ç˜ýº*i°œÈVŒ�Qû”Ñ[.�ÔmçE•ì¦eNCh�Ù
é§�É$m¿ôš"»ÌNæ(VÌmp›F¹XÈ88™ªüµ…d•XµÔÜ#�ˆŠv‘º‚F‚§Yûb

关于我如何做到这一点的任何想法,还是我需要改变我的方法?

答案
    builder.Append(ImageData)

是不正确的。你需要读取图像为byte,然后将byte []添加到multipart post。

Using HttpWebRequest to POST data/upload image using multipart/form-data查看详细信息

并确保使用http嗅探器(即fiddler)来查看它实际发送的内容。

首先,将图像加载到字节数组,然后将其转换为base64:

imgBase64 = Convert.ToBase64String(my_image_byte_array)
另一答案

我的“OpenFileDialog”名称是“file”。单击“按钮”时,将显示弹出对话框,用于选择jpg,jpeg,png图像文件,还可以添加bmp或任何图像文件类型。然后在选择图像文件后,它将显示在“PictureBox”上,我将其命名为“picboxProfileID”。

在Visual Basic中:

  file.Filter = "image file (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png | all files (*.*) | *.*"
    If (file.ShowDialog <> Windows.Forms.DialogResult.Cancel) Then
        picboxProfileID.Image = Image.FromFile(file.FileName)
        picboxProfileID.ImageLocation = file.FileName
        txtName.Text = file.FileName
        My.Computer.Network.UploadFile(file.FileName, "http://localhost/VTVTS/uploadImageSample.php")
    Else
        picboxProfileID.Image = Nothing
    End If

上传文件的目的地将上传到创建的父文件夹php文件的“images /”。

在PHP中:

<?php
$response = array();
$image = $_FILES['file'];

$imageName = $image['name'];
$imageTmpName = $image['tmp_name'];
$imageSize = $image['size'];
$imageError = $image['error'];
$imageType = $image['type'];

$fileExt = explode('.', $imageName);
$fileActualExt = strtolower(end($fileExt));

$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
    $fileNameNew = uniqid('', true).".".$fileActualExt;
    $fileDestination = 'images/'.$fileNameNew;
    $newDestination = move_uploaded_file($imageTmpName, $fileDestination);
    $response['error'] = false;
    $response['message'] = "Upload Image Successful";
}else{
    $response['error'] = true;
    $response['message'] = "You cannot upload files of this type!";
}
echo json_encode($response);

快乐的编码!

以上是关于上传Image MultiPart Form HTTPWebRequest - 将图像数据转换为字符串?的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC 同步上传文件

thinkphp的同步上传图片和异步上传图片

Ion Android发送multipart / form-data

Django处理文件上传File Uploads

[转]如何使用multipart/form-data格式上传文件

请求中上传图片