我正在使用PhotoChooserTask从Windows手机中选择图像,然后我想将此file/image
发送到服务器。
WebClient
方法UploadFile
但WebClient
中的Silverlight
没有此方法。
我试图使用我在这个论坛上找到的一些例子,但它没有用。谁能帮助我从一开始就这样做?我真的不明白Silverlight
是如何工作的。
答案 0 :(得分:0)
您可以使用Webclient类将文件上传为
private void UploadFile()
{
FileStream _data; // The file stream to be read
string uploadUri;
byte[] fileContent = new byte[_data.Length];
int bytesRead = _data.Read(fileContent, 0, CHUNK_SIZE);
WebClient wc = new WebClient();
wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
Uri u = new Uri(uploadUri);
wc.OpenWriteAsync(u, null, new object[] { fileContent, bytesRead });
}
void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
if (e.Error == null)
{
// Upload completed without error
}
}
在服务器端,您可以像
一样处理 public void ProcessRequest(HttpContext context)
{
if (context.Request.InputStream.Length == 0)
throw new ArgumentException("No file input");
if (context.Request.QueryString["fileName"] == null)
throw new Exception("Parameter fileName not set!");
string fileName = context.Request.QueryString["fileName"];
string filePath = @HostingEnvironment.ApplicationPhysicalPath + "/" + fileName;
bool appendToFile = context.Request.QueryString["append"] != null && context.Request.QueryString["append"] == "1";
FileMode fileMode;
if (!appendToFile)
{
if (File.Exists(filePath))
File.Delete(filePath);
fileMode = FileMode.Create;
}
else
{
fileMode = FileMode.Append;
}
using (FileStream fs = File.Open(filePath, fileMode))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
fs.Close();
}
}
希望它会对你有所帮助。