在c#i中将图像转换为base64字符串,然后将其发布到php脚本,该脚本将其保存为服务器中的图像文件。
php:
<?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>
和c#代码:
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;
}
}
}
}
}
这会在服务器上创建文件,但文件不起作用。 如果我使用Google Chrome提交表单数据,并使用ImageToBase64方法生成的数据,那么该文件确实可以正常工作。