今天遇到另外一种上传图片方法
用jquery.fileupload.js
<input type="file" name="file[]" multiple id="fileupload">
一个文件类型的元素
$("#fileupload").fileupload({
datatype:"json",
url: "/File/UploadFiles",
done: function (e, data) { //上传结束的操作
if (data.result[0].result != "OK") //不成功的时候 弹出消息
{
alert(data.result[0].result);
}
else
{
$("#imgshow").attr("src", data.result[0].thumbnail_url); //成功的时候显示图片
}
}
})
上面的url 处理当选择完成图片后进行的上传操作
public string path = "~/Files";
[HttpPost]
public ActionResult UploadFiles()
{
var r = new List<ViewDataUploadFilesResult>();
foreach (string file in Request.Files)
{
var statuses = new List<ViewDataUploadFilesResult>();
var headers = Request.Headers; if (string.IsNullOrEmpty(headers["X-File-Name"]))
{
UploadWholeFile(Request, statuses);
}
else
{
UploadPartialFile(headers["X-File-Name"], Request, statuses);
} JsonResult result = Json(statuses);
result.ContentType = "text/plain"; return result;
} return Json(r);
}
上面是uploadfiles方法。
ViewDataUploadFilesResult是定义的文件类
public class ViewDataUploadFilesResult
{
public string name { get; set; }
public int size { get; set; }
public string type { get; set; }
public string url { get; set; }
public string delete_url { get; set; }
public string thumbnail_url { get; set; }
public string delete_type { get; set; } public string result { set; get; }
}
有名字尺寸类型等属性
UploadWholeFile上传整个文件
private void UploadWholeFile(HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
{
for (int i = ; i < request.Files.Count; i++)
{
string result = ISValid(request.Files[i], "image");
if (result!= "OK")
{
statuses.Add(new ViewDataUploadFilesResult() { result=result});
}
}
if (statuses.Count > ) return;
for (int i = ; i < request.Files.Count; i++)
{
var file = request.Files[i]; if (!Directory.Exists(StorageRoot))
{
Directory.CreateDirectory(StorageRoot);
}
string fileExt = Path.GetExtension(file.FileName).ToLower();
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
var fullPath = Path.Combine(StorageRoot, newFileName); file.SaveAs(fullPath); statuses.Add(new ViewDataUploadFilesResult()
{
result = "OK",
name = newFileName,
size = file.ContentLength,
type = file.ContentType,
url = Path.Combine(path, Path.GetFileName(newFileName)),
delete_url = "/Home/Delete/" + newFileName,
thumbnail_url = @"data:image/png;base64," + EncodeFile(fullPath),
delete_type = "GET",
});
}
}
private void UploadPartialFile(string fileName, HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
{
if (request.Files.Count != ) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request");
var file = request.Files[];
string result = ISValid(file, "image");
if (result != "OK")
{
statuses.Add(new ViewDataUploadFilesResult() { result = result });
}
if (statuses.Count > ) return;
var inputStream = file.InputStream;
if (!Directory.Exists(StorageRoot))
{
Directory.CreateDirectory(StorageRoot);
}
string fileExt = Path.GetExtension(file.FileName).ToLower();
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
var fullName = Path.Combine(StorageRoot, newFileName); using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
{
var buffer = new byte[]; var l = inputStream.Read(buffer, , );
while (l > )
{
fs.Write(buffer, , l);
l = inputStream.Read(buffer, , );
}
fs.Flush();
fs.Close();
}
statuses.Add(new ViewDataUploadFilesResult()
{
result="OK",
name = newFileName,
size = file.ContentLength,
type = file.ContentType,
url = Path.Combine(path, Path.GetFileName(newFileName)),
delete_url = "/Home/Delete/" + newFileName,
thumbnail_url = @"data:image/png;base64," + EncodeFile(fullName),
delete_type = "GET",
});
}
上传部分文件
private string ISValid(HttpPostedFileBase file,string dirName)
{
//定义允许上传的文件扩展名
Hashtable extTable = new Hashtable();
extTable.Add("image", "gif,jpg,jpeg,png,bmp");
extTable.Add("flash", "swf,flv");
extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); //最大文件大小
int maxSize = ;
String fileName = file.FileName;
String fileExt = Path.GetExtension(fileName).ToLower(); if (file.InputStream == null || file.InputStream.Length > maxSize)
{
return "上传文件大小超过限制。";
} if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring().ToLower()) == -)
{
return "上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。";
}
return "OK";
}
isvalid验证上传文件是否合理
private string EncodeFile(string fileName)
{
return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName));
}
[HttpGet]
public void Delete(string id)
{
var filename = id;
var filePath = Path.Combine(Server.MapPath("~/Files"), filename); if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
}