3

我正在尝试使用 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–¤Ú, 3\UzL  öÔ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

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

4

2 回答 2

1
    builder.Append(ImageData)

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

请参阅Using HttpWebRequest to POST data/upload image using multipart/form-data 中的详细信息

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

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

imgBase64 = Convert.ToBase64String(my_image_byte_array)
于 2012-12-17T17:04:05.563 回答
0

我的“OpenFileDialog”名称是“文件”。单击“按钮”时,将弹出一个对话框,用于选择 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);

快乐编码!

于 2017-12-16T17:49:12.607 回答