来自c#的HTTP POST,php将POST另存为图像
在c#中,我将图像转换为base64字符串,然后将其发布到php脚本,该脚本将其保存为服务器中的图像文件 php:来自c#的HTTP POST,php将POST另存为图像,c#,php,post,httpwebrequest,C#,Php,Post,Httpwebrequest,在c#中,我将图像转换为base64字符串,然后将其发布到php脚本,该脚本将其保存为服务器中的图像文件 php: <?php file_put_contents($_POST["name"], base64_decode($_POST["file"])); ?> <html> <body> <form action="<?php $_PHP_SELF ?>" method="POST"> <input type="tex
<?php
file_put_contents($_POST["name"], base64_decode($_POST["file"]));
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
<input type="text" name="name" />
<input type="text" name="file" />
<input type="submit" />
</form>
</body>
</html>
这会在服务器上创建文件,但该文件不起作用。
如果我使用Google chrome和ImageToBase64方法生成的数据一起提交表单数据,那么该文件确实有效。既然您使用POST,为什么不将整个图像作为字节数组而不是字符串进行POST?字符串更适合GET请求。我该如何做?我认为一篇文章应该是一个字符串?首先,你需要理解post和GET之间的区别。你可以在这里查看如何发布数据:你能解释一下“文件不工作”是什么意思吗?我建议在原始文件和保存的文件之间执行二进制比较,以检测任何问题,例如,如果数据被截断,而文件只是垃圾。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Net;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string param = "name=image.jpg&file=" + ImageToBase64(p.Image);
post(param, "urlToPHPfileShown");
}
public string ImageToBase64(Image image)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
public string post(string param, string url)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
string postArgs = param;
req.Method = "POST";
req.CookieContainer = new CookieContainer();
req.ContentType = @"application/x-www-form-urlencoded";
byte[] buffer = System.Text.ASCIIEncoding.UTF8.GetBytes(postArgs);
req.ContentLength = buffer.Length;
req.AllowAutoRedirect = true;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
using (Stream respStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(respStream))
{
string s = sr.ReadToEnd();
return s;
}
}
}
}
}