VB.NET 文件上传至服务器源码

VB.NET · 08-14 · 323 人浏览

PHP后端代码:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
    $target_dir = "uploads/";
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    $current_time = date("Ymd_His");
    $file_extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
    $new_file_name = $current_time . "." . $file_extension;
    $target_file = $target_dir . $new_file_name;

    if (file_exists($target_file)) {
        echo "抱歉,文件已存在。";
        exit;
    }

    $allowed_types = array("jpg", "png", "jpeg", "gif", "pdf", "txt");
    $file_type = strtolower($file_extension);

    if (!in_array($file_type, $allowed_types)) {
        echo "抱歉,仅允许上传 JPG, JPEG, PNG, GIF, PDF 和 TXT 文件。";
        exit;
    }

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "文件 ". htmlspecialchars($new_file_name). " 已上传成功。";
    } else {
        echo "抱歉,上传文件时发生错误。";
    }
} else {
    echo "未上传任何文件。";
}
?>

VB.NET 上传代码(添加一个按钮,选择文件并执行上传。环境:.NET4.5.1):

Imports System.Net

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim openFileDialog As New OpenFileDialog()
        If openFileDialog.ShowDialog() = DialogResult.OK Then
            Dim filePath As String = openFileDialog.FileName
            UploadFile(filePath)
        End If
    End Sub
    Private Sub UploadFile(filePath As String)
        '使用TLS12安全协议连接
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
        Dim url As String = "https://lx.lxjc.com/sc.php"

        Using client As New WebClient()
            Try
                Dim response As Byte() = client.UploadFile(url, filePath)
                Dim responseString As String = System.Text.Encoding.UTF8.GetString(response)
                MessageBox.Show("上传结果: " & responseString)
            Catch ex As Exception
                MessageBox.Show("发生错误: " & ex.Message)
            End Try
        End Using
    End Sub
End Class



* 人工审核评论,通过后即可正常显示。软件建议请添加微信