利用webservices实现图片远程上传
首先建立webservice环境,创建实现函数
[WebService(Namespace = "http://jason.han%22,description/="在WebSerive 上传图片")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class WebServiceUpload : System.Web.Services.WebService
{
[WebMethod(Description = "上传服务器图片信息,返回是否成功")]
public string UploadFile(byte[] fs,string FileName)
{
try
{
MemoryStream m = new MemoryStream(fs);//定义并实例化一个内存流,来存放上传的图片二进制流
FileStream f = new FileStream(Server.MapPath(".") + \\images" + FileName, FileMode.Create);//把内存里的文件写入文件流
m.WriteTo(f);
m.Close();
f = null;
m = null;
return "文件上传成功";
}
catch(Exception ex)
{
return ex.Message.ToString();
}
}
}
前端文件上传方法实现
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
System.Web.HttpFileCollection oFiles;
oFiles = System.Web.HttpContext.Current.Request.Files;
if (oFiles.Count < 1)
{
Response.Write("请选择文件");
Response.End();
}
string FilePath = oFiles[0].FileName;
if (FilePath == null || FilePath == "")
{
Response.Write("请重新选择图片");
Response.End();
}
string fileName = FilePath.Substring(FilePath.LastIndexOf("\\") + 1);
try
{
byte[] b = new byte[oFiles[0].ContentLength];
System.IO.Stream fs;
PicUploadDemo.WebServiceUpload oWSUpload;//调用webservices
oWSUpload = new WebServiceUpload();
fs = (System.IO.Stream)oFiles[0].InputStream;
fs.Read(b, 0, oFiles[0].ContentLength);//将输入流读入二进制数组中
Response.Write(oWSUpload.UploadFile(b,fileName));
fs.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
}
}