webService上传图片
webService
/// <summary>
/// 上传图片webServer 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public bool UpdateFile(byte[] content, string pathand,string filename)
{
string pathandname = pathand + filename;
int index = pathandname.LastIndexOf(".");
if (index == 0)
{
return false;
}
else
{
string extended = string.Empty;
if (index + 1 == pathandname.Length)
{
return false;
}
else
{
extended = pathandname.Substring(index + 1);
if (extended == "jpeg" || extended == "gif" || extended == "jpg" || extended == "bmp" || extended == "png")
{
try
{
if (!Directory.Exists(@pathand))//若文件夹不存在则新建文件夹
{
Directory.CreateDirectory(@pathand); //新建文件夹
}
//File.WriteAllBytes(Server.MapPath(pathandname), content);
File.WriteAllBytes(pathandname, content);
return true;
}
catch (Exception ex)
{
return false;
}
}
else
{
return false;
}
}
}
}
}
//测试
private void btnSaveServer_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string pathand = CommonClass.Config.GetAppSettings<string>("ProductImageUrl", @"D:\FSTERP\ProductImage\");
string imagename = "mylove";
bool uploadResult = UploadImageWebService(fileDialog.FileName, pathand, imagename);
if (uploadResult)
MessageBox.Show("上传成功!");
else
MessageBox.Show("上传失败!");
}
}
/// <summary>
/// 上传图片[通过webServer]
/// </summary>
/// <param name="filename">选择图片路径[默认选择文件包括后缀名]</param>
/// <param name="pathand">上传服务器文件夹[文件夹不存在则新建]</param>
/// <param name="imagename">上传后图片文件名[不包括后缀名]</param>
/// <returns>上传结果</returns>
public bool UploadImageWebService(string filename, string pathand, string imgname)
{
string extension = Path.GetExtension(filename).ToLower().Replace(".", "");
string paramSuffix = "|" + CommonClass.Config.GetAppSettings<string>("ImageFormat", "jpg|jpge|gif|bmp|png") + "|";
int pi = paramSuffix.IndexOf("|" + extension + "|");
if (pi < 0)
{
MessageBox.Show("仅能上传jpg|jpge|gif|bmp|png格式的图片!");
return false;
}
else
{
FileInfo fileInfo = new FileInfo(filename);
if (fileInfo.Length > 20480)
{
MessageBox.Show("上传的图片不能大于20K");
}
else
{
//Stream file = fileDialog.OpenFile();
FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, bytes.Length);
//实例化WebService服务。ServiceReference1是我们在添加引用时设置的命名空间
WebService.WebService1 webservice = new FSTERP.WebService.WebService1();
DateTime time = DateTime.Now;
//重命名图片的名称与路径
//string pathand = CommonClass.Config.GetAppSettings<string>("ProductImageUrl", @"D:\FSTERP\ProductImage\");
string imagename = imgname + "." + extension;
//string pathandname = pathand + imagename;
if (webservice.UpdateFile(bytes, pathand, imagename))
{
return true;
}
else
{
return false;
}
}
}
return false;
}
测试图片