using System;
using System.IO;
namespace puruite.Helps
{
class Upload
{
public static string UploadImage(string fileName, Stream fileData)
{
// 获取file后缀
string ext = Path.GetExtension(fileName);
// 随机文件名
string newFileName = DateTime.Now.ToFileTime().ToString() + FunctionHelper.RandStr(10);
string currentPath = AppDomain.CurrentDomain.BaseDirectory;
string savePath = "/uploads";
string fullSavePath = currentPath + savePath;
if (!Directory.Exists(fullSavePath))
{
Directory.CreateDirectory(fullSavePath);
}
string fullPath = fullSavePath + "/" + newFileName + ext;
string returnPath = savePath +"/" + newFileName + ext;
BinaryReader bReader = new BinaryReader(fileData);
FileStream fStream = new FileStream(fullPath, FileMode.CreateNew);
BinaryWriter bWriter = new BinaryWriter(fStream);
bWriter.Write(bReader.ReadBytes((int)fileData.Length));
bWriter.Close();
fStream.Close();
return returnPath;
}
}
}
使用
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = false;
fileDialog.Filter = "图片|*.jpg;*.png;*.gif;*.bmp;*.jpeg";
Nullable<bool> isShow = fileDialog.ShowDialog();
if(isShow == true)
{
string fileName = fileDialog.FileName;
BitmapImage image = new BitmapImage(new Uri(fileName));
this.logoImage.Source = image;
string newFile = Upload.UploadImage(fileName, fileDialog.OpenFile());
this.logoTxt.Text = newFile;
}
显示
string logo = setting["logo"].ToString();
this.logoTxt.Text = logo;
if (logo != "")
{
string logoPath = AppDomain.CurrentDomain.BaseDirectory + logo;
this.logoImage.Source = new BitmapImage(new Uri(logoPath, UriKind.RelativeOrAbsolute));
}