Wp7: 調用攝像頭拍照並上傳圖片(完整版)


本例通過webclient上傳圖片,首先在Mian.xaml.cs中:

private void SelectButton_Click(object sender, RoutedEventArgs e)
{
PhotoChooserTask task = new PhotoChooserTask();
task.Completed += task_Completed;
task.Show();
}

private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;

const int BLOCK_SIZE = 4096;

Uri uri = new Uri("http://localhost:13235/WebClientUpLoadHandler.ashx", UriKind.Absolute);

WebClient wc = new WebClient();
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;

// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};

// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};

// Write to the WebClient
wc.OpenWriteAsync(uri, "POST");
}

在asp.net  server端新建一個ashx handler:

    /// <summary>
///新建一個ashx類處理上傳數據
/// </summary>
public class WebClientUpLoadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//獲取從Silverlight客戶端傳來的信息
int length = context.Request.ContentLength;
byte[] bytes = context.Request.BinaryRead(length);
string uploadFolder = System.AppDomain.CurrentDomain.BaseDirectory + "\\uploadvoice";
//目錄不存在則新建
//if (!System.IO.Directory.Exists(uploadFolder))
//{
// System.IO.Directory.CreateDirectory(uploadFolder);
//}
System.IO.FileMode fileMode = System.IO.FileMode.Create;

////寫入文件
try
{
using (System.IO.FileStream fs = new System.IO.FileStream(uploadFolder + "\\" + "name", fileMode, System.IO.FileAccess.Write))
{
fs.Write(bytes, 0, bytes.Length);
} context.Response.Write("服務器端成功");
}
catch { context.Response.Write("寫入失敗"); }


}

public bool IsReusable
{
get
{
return false;
}
}

}




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM