首页 > 代码库 > WP8_(windows phone环境下)上传文件从C#到php接口
WP8_(windows phone环境下)上传文件从C#到php接口
在windows phone环境下,将手机上的图片上传到服务端(php环境);
注意事项:在上传的地方,头文件中name,例如name= img,则在php服务端处理时
,需要约定好 存取一致 php:$_FILES[‘img‘][‘name‘],如若两端的name不相同则服务端无法正确获取上传的文件;
public class UploadSrv
{
#region 选择图片
/// <summary>
/// 打开照相机
/// </summary>
public void OpenCamera()
{
CameraCaptureTask cameraCapture = new CameraCaptureTask();
cameraCapture.Completed += photoChooser_Completed;
cameraCapture.Show();
}
/// <summary>
/// 选择图片
/// </summary>
public void ChooseImage()
{
PhotoChooserTask photoChooser = new PhotoChooserTask();
photoChooser.Completed += photoChooser_Completed;
photoChooser.Show();
}
void photoChooser_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
Upload(e.ChosenPhoto);
//BitmapImage bitmap = new BitmapImage();
//bitmap.SetSource(e.ChosenPhoto);
//Image img = new Image();
//img.Source = bitmap;
//if (e.ChosenPhoto != null)
//{
// Stream s = UploadFile.Compression(e.ChosenPhoto);
// bytepic = StreamToBytes(s);
// Encoding myEncoding = Encoding.GetEncoding("utf-8");
// strpic = Convert.ToBase64String(bytepic);
// ExistsPic = true;
//}
}
}
#endregion
/// <summary>
/// 上传
/// </summary>
/// <param name="argStream"></param>
void Upload(Stream argStream)
{
if (!DeviceNetworkInformation.IsNetworkAvailable)
{
MessageBox.Show("请开启网络连接..");
return;
}
if (!DeviceNetworkInformation.IsCellularDataEnabled && !DeviceNetworkInformation.IsWiFiEnabled)
{
MessageBox.Show("请开启网络连接...");
return;
}
byte[] bytes = new byte[argStream.Length];
argStream.Seek(0, SeekOrigin.Begin);
while (argStream.Read(bytes, 0, bytes.Length) > 0) ;
string fileName = Constant.Mac + ".png";//此处指定了上传文件名 ,Constant.Mac是自己定义的常量
Dictionary<string, object> postParameters = new Dictionary<string, object>();
string contentType = "multipart/form-data";//"image/jpeg";//"multipart/form-data";//"application/octetstream";//"image/jpeg";//"multipart/form-data";
FileParameter param = new FileParameter(bytes, fileName, contentType);
postParameters.Add(fileName, param);
HttpMultipartFormRequest req = new HttpMultipartFormRequest();
req.AsyncHttpRequest(Constant.URL_IMG_UploadPortrait, postParameters, null); //自己定义的常量 Post上传到的网址
//Sys.ProgressBarBase.Show(true);
}
#region 其他方法(未使用)
/// <summary>
/// 字节流转换byte
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
/// <summary>
/// 压缩图片,只调整质量,不调整分辨率
/// </summary>
/// <param name="soucre">图片流</param>
/// <param name="quality">质量1-100</param>
Stream Compression(Stream soucre, int quality)
{
//var quality = 80;
soucre.Seek(0, SeekOrigin.Begin);
var p = quality / 100.0;
var writeableBitmap = PictureDecoder.DecodeJpeg(soucre);
var width = writeableBitmap.PixelWidth * p;
var height = writeableBitmap.PixelHeight * p;
var outstream = new MemoryStream();
writeableBitmap.SaveJpeg(outstream, (int)width, (int)height, 0, quality);
outstream.Seek(0, SeekOrigin.Begin);
return outstream;
}
/// <summary>
/// 根据文件扩展名获取文件类型
/// </summary>
/// <param name="fileName">文件名</param>
/// <returns></returns>
string GetContentType(string fileName)
{
var fileExt = System.IO.Path.GetExtension(fileName);
return GetCommonFileContentType(fileExt);
}
/// <summary>
/// 获取通用文件的文件类型
/// </summary>
/// <param name="fileExt">文件扩展名.如".jpg",".gif"等</param>
/// <returns></returns>
string GetCommonFileContentType(string fileExt)
{
switch (fileExt)
{
case ".jpg":
case ".jpeg":
return "image/jpeg";
case ".gif":
return "image/gif";
case ".bmp":
return "image/bmp";
case ".png":
return "image/png";
default:
return "application/octetstream";
}
}
#endregion
}
以下2个类是实际上传文件处理类:
/// <summary>
/// 文件类型数据的内容参数
/// </summary>
public class FileParameter
{
// 文件内容
public byte[] File { get; set; }
// 文件名
public string FileName { get; set; }
// 文件内容类型
public string ContentType { get; set; }
public FileParameter(byte[] file) : this(file, null) { }
public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
public FileParameter(byte[] file, string filename, string contentType)
{
File = file;
FileName = filename;
ContentType = contentType;
}
}
/// <summary>
/// 文件上传类(数据与文件http请求)
/// </summary>
public class HttpMultipartFormRequest
{
#region Data Members
private readonly Encoding DefaultEncoding = Encoding.UTF8;
private ResponseCallback m_Callback;
private byte[] m_FormData;
#endregion
#region Constructor
public HttpMultipartFormRequest()
{
}
#endregion
#region Delegate
public delegate void ResponseCallback(string msg);
#endregion
/// <summary>
/// 传单个文件(暂不用)
/// </summary>
/// <param name="postUri"></param>
/// <param name="argbytes"></param>
/// <param name="callback"></param>
public void AsyncHttpRequest(string postUri, byte[] argbytes, ResponseCallback callback = null)
{
// 随机序列,用作防止服务器无法识别数据的起始位置
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
// 设置contentType
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
// 将数据转换为byte[]格式
m_FormData = http://www.mamicode.com/argbytes;//GetMultipartFormData(postParameters, formDataBoundary);
// 回调函数
m_Callback = callback;
// 创建http对象
HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri(postUri));
// 设为post请求
request.Method = "POST";
request.ContentType = contentType;
// 请求写入数据流
request.BeginGetRequestStream(GetRequestStreamCallback, request);
}
/// <summary>
/// 传多个文件
/// </summary>
/// <param name="postUri">请求的URL</param>
/// <param name="postParameters">[filename,FileParameter]</param>
/// <param name="callback">回掉函数</param>
public void AsyncHttpRequest(string postUri, Dictionary<string, object> postParameters, ResponseCallback callback)
{
// 随机序列,用作防止服务器无法识别数据的起始位置
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
// 设置contentType
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
// 将数据转换为byte[]格式
m_FormData = http://www.mamicode.com/GetMultipartFormData(postParameters, formDataBoundary);
// 回调函数
m_Callback = callback;
// 创建http对象
HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri(postUri));
// 设为post请求
request.Method = "POST";
request.ContentType = contentType;
// 请求写入数据流
request.BeginGetRequestStream(GetRequestStreamCallback, request);
}
private void GetRequestStreamCallback(IAsyncResult ar)
{
HttpWebRequest request = ar.AsyncState as HttpWebRequest;
using (var postStream = request.EndGetRequestStream(ar))
{
postStream.Write(m_FormData, 0, m_FormData.Length);
postStream.Close();
}
request.BeginGetResponse(GetResponseCallback, request);
}
private void GetResponseCallback(IAsyncResult ar)
{
// 处理Post请求返回的消息
try
{
HttpWebRequest request = ar.AsyncState as HttpWebRequest;
HttpWebResponse response = request.EndGetResponse(ar) as HttpWebResponse;
using (StreamReader reader = new StreamReader(response.GetResponseStream(), DBCSEncoding.GetDBCSEncoding("gb2312")))
{
string msg = reader.ReadToEnd();
if (m_Callback != null)
{
m_Callback(msg);
}
}
}
catch (Exception e)
{
string a = e.ToString();
if (m_Callback != null)
{
m_Callback(string.Empty);
}
}
}
private byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new MemoryStream();
bool needsCLRF = false;
foreach (var param in postParameters)
{
if (needsCLRF)
{
formDataStream.Write(DefaultEncoding.GetBytes("\r\n"), 0, DefaultEncoding.GetByteCount("\r\n"));
}
needsCLRF = true;
if (param.Value is FileParameter)
{
FileParameter fileToUpload = (FileParameter)param.Value;
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
boundary,
"img", // param.Key, //此处如果是请求的php,则需要约定好 存取一致 php:$_FILES[‘img‘][‘name‘]
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
// 将与文件相关的header数据写到stream中
formDataStream.Write(DefaultEncoding.GetBytes(header), 0, DefaultEncoding.GetByteCount(header));
// 将文件数据直接写到stream中
formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
}
else
{
string postData = http://www.mamicode.com/string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(DefaultEncoding.GetBytes(postData), 0, DefaultEncoding.GetByteCount(postData));
}
}
string tailEnd = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(DefaultEncoding.GetBytes(tailEnd), 0, DefaultEncoding.GetByteCount(tailEnd));
// 将Stream数据转换为byte[]格式
formDataStream.Position = 0;
byte[] formData = http://www.mamicode.com/new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
}
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
其他参考资料:
直接运行html,选择上传文件后,点提交,即可上传;
注意:name=“file” id=“file” 要与php服务端的 名字一致;
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
其他参考代码:
http://314858770.iteye.com/blog/720456
http://stackoverflow.com/questions/10124150/send-file-in-post-request-with-windows-phone-7
http://stackoverflow.com/questions/6977615/to-post-image-file-in-windows-phone-7-application
http://chriskoenig.net/2011/08/19/upload-files-from-windows-phone/
关键词: C#上传文件到php
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------