如何在C#中通过WebClient上传文件时附带传递myValue参数
解决方案
要在上传文件时同时传递myValue参数,你需要将请求格式改为multipart/form-data(这是同时传输文件和表单字段的标准方式),替代原来的binary/octet-stream。以下是两种实现方式:
方式一:使用WebClient实现
string message, title, defaultValue; string myValue; message = "Enter Image name please"; title = "Image name"; defaultValue = "1"; myValue = Interaction.InputBox(message, title, defaultValue, 100, 100); using (System.Net.WebClient client = new System.Net.WebClient()) { // 添加会话密钥头部 client.Headers.Add("SESSION-KEY", App.Session_Key); // 定义multipart请求的边界标识 string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); client.Headers.Add("Content-Type", $"multipart/form-data; boundary={boundary}"); try { // 读取本地文件字节 byte[] fileBytes = File.ReadAllBytes("temp.png"); // 组装multipart请求内容 using (MemoryStream ms = new MemoryStream()) { // 写入myValue参数 string paramContent = $"--{boundary}\r\nContent-Disposition: form-data; name=\"myValue\"\r\n\r\n{myValue}\r\n"; ms.Write(System.Text.Encoding.UTF8.GetBytes(paramContent), 0, paramContent.Length); // 写入文件内容 string fileContentHeader = $"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"temp.png\"\r\nContent-Type: image/png\r\n\r\n"; ms.Write(System.Text.Encoding.UTF8.GetBytes(fileContentHeader), 0, fileContentHeader.Length); ms.Write(fileBytes, 0, fileBytes.Length); // 写入请求结束边界 string endBoundary = $"\r\n--{boundary}--\r\n"; ms.Write(System.Text.Encoding.UTF8.GetBytes(endBoundary), 0, endBoundary.Length); // 发送上传请求 byte[] result = client.UploadData(Screenshot.Properties.Resources.APIURL + "Upload.php", "POST", ms.ToArray()); // 解析响应内容(可选) string response = System.Text.Encoding.UTF8.GetString(result); } } catch (Exception ex) { // 异常处理 Console.WriteLine($"上传出错: {ex.Message}"); } }
方式二:使用HttpClient实现(.NET Framework 4.5+)
如果你的项目支持更高版本的.NET框架,用HttpClient代码会更简洁:
string message, title, defaultValue; string myValue; message = "Enter Image name please"; title = "Image name"; defaultValue = "1"; myValue = Interaction.InputBox(message, title, defaultValue, 100, 100); using (HttpClient client = new HttpClient()) { // 添加会话密钥头部 client.DefaultRequestHeaders.Add("SESSION-KEY", App.Session_Key); using (MultipartFormDataContent formContent = new MultipartFormDataContent()) { // 添加myValue参数 formContent.Add(new StringContent(myValue), "myValue"); // 添加要上传的文件 formContent.Add(new ByteArrayContent(File.ReadAllBytes("temp.png")), "file", "temp.png"); // 发送POST请求 HttpResponseMessage response = await client.PostAsync(Screenshot.Properties.Resources.APIURL + "Upload.php", formContent); response.EnsureSuccessStatusCode(); // 确保请求成功 string responseContent = await response.Content.ReadAsStringAsync(); } }
服务器端(Upload.php)适配代码
你的PHP接口需要能解析multipart数据,示例如下:
<?php // 获取传递的myValue参数 $myValue = $_POST['myValue'] ?? ''; // 获取上传的文件 $uploadFile = $_FILES['file'] ?? null; if ($uploadFile && $uploadFile['error'] === UPLOAD_ERR_OK) { // 定义文件存储路径 $targetDir = 'uploads/'; if (!is_dir($targetDir)) mkdir($targetDir, 0755, true); $targetPath = $targetDir . basename($uploadFile['name']); // 移动临时文件到目标路径 if (move_uploaded_file($uploadFile['tmp_name'], $targetPath)) { echo json_encode(['status' => 'success', 'myValue' => $myValue, 'filePath' => $targetPath]); } else { echo json_encode(['status' => 'error', 'message' => '文件保存失败']); } } else { echo json_encode(['status' => 'error', 'message' => '文件上传失败']); } ?>
内容的提问来源于stack exchange,提问作者govtexam guru
相关产品推荐
相关产品推荐

