在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 = 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 = 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 = 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 = 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

--------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------

WP8_(windows phone环境下)上传文件从C#到php接口的更多相关文章

  1. IIS环境下上传文件失败

    跟随学习代码练习 php 上传文件,一开始是点击按钮后没有反应,不知道是否成功,使用 var_dump($_FILES) 查看,发现空空如也.遂百度一下,发现基本代码应如下 <form acti ...

  2. Git在windows下上传文件至github流程

    github是开发者分享的一个平台,这里不多说,想要上传文件至github需要有一个开发者账号,还需要在windows下安装好了git. 做好准备工作之后,接下来操作 一:登录github,创建项目 ...

  3. docker在windows下上传文件到容器

    我的系统是windows10,docker是用DockerToolbox工具安装的,安装完之后会默认挂载Windows的C:/Users目录,在docker里面对应路径是/c/Users,docker ...

  4. .NET环境下上传和下载Word文件

    一.上传Word文档或者其他文档 1.简单地上传文件的web服务方法如下 [WebMethod] public void UploadFile() { using (TransactionScope ...

  5. 使用PuTTY在Windows中向Linux上传文件

    为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/SJQ. http://www.cnblogs.com/shijiaqi1066/p/3843207.html ...

  6. 【阿里云产品公测】ACE下上传文件永久存储实践

    本帖主要内容: ;$,=VB:'   在阿里云的ACE下,我是如何实现让上传的文件永久保存的? ,%"!8T   本文以PHP为例,具体知识点如下: WD# 96V   第一,扩展服务“存储 ...

  7. Windows服务器修改网站上传文件的大小限制

    ASP程序 方法一: 修改该网站的的最大上传文件的大小限制 在Windows server上会出现上传大小受限制的问题,这是由于windows server的IIS管理器做了限制所致,IIS默认设置是 ...

  8. 不用FTP,直接Windows与Linux下互传文件

    直接上传文件到Linux[1] Linux上输入命令:rz 直接下载Linux中的文件[2] 使用命令: sz 文件名 网上看到这个帖子,觉得很实用,转载保存 下载一个部署文件夹,到本地电脑 . 两步 ...

  9. window下上传文件至linux(windows下如何访问linux)

    ========相信我,按照步骤来一定能成功====== 我将从三个方面来说明:为什么要搭建访问服务器.如何搭建访问服务器.windows如下访问 为什么要搭建访问Linux服务器 我们都知道,服务器 ...

随机推荐

  1. GL_GL系列 - 总账系统基础(概念)

    2014-07-07 Created By BaoXinjian

  2. c++,opencv播放视频

    #include <opencv2\opencv.hpp>#include <iostream> using namespace cv;using namespace std; ...

  3. unix 中 ps -ef命令详解

    ps -ef 查看正在活动的进程 ps -ef |grep abc 查看含有"abc"的活动进程 ps -ef |grep -v abc 查看不含abc的活动进程 1)ps a 显 ...

  4. JMeter使用技巧

    在这此对新版本jmeter的学习+温习的过程,发现了一些以前不知道的功能,所以,整理出来与大分享.本文内容如下. 如何使用英文界面的jmeter 如何使用镜像服务器 Jmeter分布式测试 启动Deb ...

  5. Python标准库04 文件管理 (部分os包,shutil包)

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 在操作系统下,用户可以通过操作系统的命令来管理文件,参考linux文件管理相关命令 ...

  6. list,set,map,数组之间的相互转换详细解析

    1.list转setSet set = new HashSet(new ArrayList()); 2.set转listList list = new ArrayList(new HashSet()) ...

  7. MS Sql Server 中主从库的配置和使用介绍(转)

    网站规模到了一定程度之后,该分的也分了,该优化的也做了优化,但是还是不能满足业务上对性能的要求:这时候我们可以考虑使用主从库. 主从库是两台服务器上的两个数据库,主库以最快的速度做增删改操作+最新数据 ...

  8. dwr入门

    dwr2.0的jar包,还需要同时导入log4j.jar和commons-loggin.jar 首先是配置文件: <!-- DWR配置 --> <servlet> <se ...

  9. 用inno Setup制作web项目安装包

    http://www.cnblogs.com/xionghui/archive/2012/03/22/2411207.html 用inno Setup制作安装包 新建一个文件夹exambody,放ap ...

  10. 小知识:如何解压cpio.gz文件

    第一种方法: zcat xxxx.cpio.gz | cpio -idmv 第二种方法 :第一步: gunzip xxxx.cpio.gz第二步:cpio -idmv < xxxx.cpio # ...