vb.net 上传图像多部分表单 HTTPWebRequest - 将图像数据转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13918238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:34:45  来源:igfitidea点击:

Uploading Image MultiPart Form HTTPWebRequest - Getting Image Data To String?

vb.netimagefile-uploadhttpwebrequeststringbuilder

提问by Chris

I am trying to upload a multi-part form with HTTPWebRequest & all is ok until I added an image to upload, mainly I am trying to do exactly the same request as a browser makes which looks like this:

我正在尝试使用 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--

I am lost on how to format / read the image to set it into the request that I am making below:

我不知道如何格式化/读取图像以将其设置为我在下面提出的请求:

            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()

At the moment it is simply posting "System.Drawing.Bitmap" as the image data but I am not sure how to get the same raw data for the image that looks like this:

目前它只是将“System.Drawing.Bitmap”作为图像数据发布,但我不确定如何为看起来像这样的图像获取相同的原始数据:

    J??Y¨e?Ln????/?§úD5y?C÷Cy>?'t;fm—=?w:?/E±?ù?$á@%Pc>×    ?gw.2Ab“:?óù:?ˉìh6àZ§ó?g£?húD6¨?^ú2?`?¨L?Y???CX#I“èì?j|L??'|¥?Eb??Q–¤ú,?3\UzL????oj4??±'u?c?#?o?`?F>·o—??????????yo*i°?èV??Q?”?[.??m?E?ì|eNCh?ù
é§?é$m???"?ìN?(Vìmp?F1Xè88?aüμ…d?Xμ?ü#???v‘o?F?§Y?b

Any ideas on how I could do this or would I need to change my methods?

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

回答by urlreader

    builder.Append(ImageData)

is not correct. you need read the image as byte, then add the byte[] to the multipart post.

是不正确的。您需要将图像读取为字节,然后将字节 [] 添加到多部分帖子中。

see details at Using HttpWebRequest to POST data/upload image using multipart/form-data

请参阅使用 HttpWebRequest 使用 multipart/form-data POST 数据/上传图像中的详细信息

and make sure use a http sniffer (i.e. fiddler) to see what it is actually sending.

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

first, load image into byte array, then convert it to base64:

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

imgBase64 = Convert.ToBase64String(my_image_byte_array)

回答by Sauer Vousstheitroad

My "OpenFileDialog" name is "file". When a "button" is clicked it will show a pop up dialog for selecting jpg, jpeg, png image files, it can also add bmp or any image file type. Then after the selection of a image file it will show on "PictureBox" i name it as "picboxProfileID".

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

In Visual Basic:

在 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

The destination of the file uploaded will be uploaded on the "images/" of the parent folder php file created.

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

In PHP:

在 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);

Happy Coding!

快乐编码!