string _fileNamePath = "";
try
{
_fileNamePath = context.Request.Form["upfile"];
//开始上传
string _savedFileResult = UpLoadFile(_fileNamePath);
context.Response.Write(_savedFileResult);
}
catch
{
context.Response.Write("0|error|上传提交出错");
}
2、
复制代码 代码如下:
//生成将要保存的随机文件名
string fileName = GetFileName() + fileNameExt;
//物理完整路径
string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
//检查是否有该路径 没有就创建
if (!Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
///创建WebClient实例
WebClient myWebClient = new WebClient();
//设定windows网络安全认证 方法1
myWebClient.Credentials = CredentialCache.DefaultCredentials;
//要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
//FileStream fs = OpenFile();
BinaryReader r = new BinaryReader(fs);
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(toFile, "PUT",fileNamePath);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(toFile, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
3、检查是否合法的上传文件
复制代码 代码如下:
private bool CheckFileExt(string _fileExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg" };
for (int i = 0; i < allowExt.Length; i++)
{
if (allowExt[i] == _fileExt) { return true; }
}
return false;
}
4、生成要保存的随即文件名
复制代码 代码如下:
public static string GetFileName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
serial.Append(rd.Next(0, 999999).ToString());
return serial.ToString();
}
Ok,基本上这个批量上传图片的JQuery+ajax方式实现的程序完成了。如果你要上传word文档,pdf文件,只要稍作修改,就可以实现了。
您可能感兴趣的文章: