一、微软自带
界面
html:
<td align="center">
照片上传
</td>
<td>
<p id="myFiles">
<asp:FileUpload ID="fup_files" runat="server" class="TextBox form-control display-inline"
Style="width: 60%;" type="file" /><img runat="server" id="images" src="../../../images/4.png"
width="34" height="34"><br />
<font color="red">照片名为字母、数字</font> <span id="insert"></span>
</p>
</td>
.cs代码:
/// <summary>
/// 附件保存
/// </summary>
private void AddFile()
{
if (fup_files.HasFile)
{
string path = "/Files/";
if (!Directory.Exists(Server.MapPath(path)))
{
Directory.CreateDirectory(Server.MapPath(path));
}
fup_files.SaveAs(Server.MapPath(path) + fup_files.FileName);
path_temp = path + fup_files.FileName;
}
}
二、Js
界面:
html:
<table width="100%">
<tr>
<td>
<a href="javascript:;" class="files">
<input type="file" id="FileUpload2" name="FileUpload2" οnchange="AttachUpload2('AttachList','FileUpload2');" /></a>
<span class="uploading">正在上传,请稍候...</span>
</td>
</tr>
<tr>
<td>
<div id="AttachList" class="attach_list">
<ul>
<asp:Repeater ID="rptAttach" runat="server">
<ItemTemplate>
<li>
<input name="hidFileName" type="hidden" value="<%#Eval("size")%>|<%#Eval("title")%>|<%#Eval("filepath")%>" />
<b class="close1" title="删除" οnclick="DelAttachLi(this);">删除</b>
<span class="title">附件:<a style="text-decoration: underline; color: blue" href='personal_document_down.aspx?p=<%#Eval("filepath")%>' title="点击可下载" id="a_uploadfile"><%#Eval("title")%></a></span>
<span class="fsize">
<%#Eval("size")%></span>
<a href="javascript:;" class="upfile"><input type="file" name="FileUpdate" οnchange="AttachUpdate('hidFileName',this);" /></a><span
class="uploading">正在更新...</span> </li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</td>
</tr>
</table>
JS:
function AttachUpload2(repath, uppath) {
var submitUrl = "../../../tools/upload_ajax.ashx?action=AttachFile&UpFilePath=" + uppath;
//开始提交
$("#form1").ajaxSubmit({
beforeSubmit: function (formData, jqForm, options) {
//隐藏上传按钮
$("#" + uppath).parent().hide();
//显示LOADING图片
$("#" + uppath).parent().nextAll(".uploading").eq(0).show();
},
success: function (data, textStatus) {
if (data.msg == 1) {
var listBox = $("#" + repath + " ul");
var newLi = '<li>'
+ '<input name="hidFileName" type="hidden" value="' + data.mssite + '|' + data.mstitle + "|" + data.msgbox + '" />'
+ '<input name="txtbox" type="hidden" value="' + data.msgbox + '" />'
+ '<b class="close" title="删除" οnclick="DelAttachLi(this);"></b>'
+ '附件:<span class="title" name="mstitle">' + data.mstitle + '</span>'
+ '大小:<span name="mssite" class="fsize">' + data.mssite + '</span>'
+ '<a href="javascript:;" class="upfile"><input type="file" name="FileUpdate" οnchange="AttachUpdate2(\'hidFileName\',this);" /></a>'
+ '<span class="uploading">正在更新...</span>'
+ '</li>';
listBox.append(newLi);
}
else {
alert(data.msgbox);
}
$("#" + uppath).parent().show();
$("#" + uppath).parent().nextAll(".uploading").eq(0).hide();
document.getElementById(uppath).value = "";
},
error: function (data, status, e) {
alert("上传失败,错误信息:" + e);
$("#" + uppath).parent().show();
$("#" + uppath).parent().nextAll(".uploading").eq(0).hide();
},
url: submitUrl,
type: "post",
dataType: "json",
timeout: 600000
});
};
.CS
#region 上传附件处理=====================================
private void AttachFile(HttpContext context)
{
string _upfilepath = context.Request.QueryString["UpFilePath"]; //取得上传的对象名称
HttpPostedFile _upfile = context.Request.Files[_upfilepath];
bool _iswater = false; //默认不打水印
bool _isthumbnail = false; //默认不生成缩略图
if (_upfile == null)
{
context.Response.Write("{\"msg\": 0, \"msgbox\": \"请选择要上传文件!\"}");
return;
}
Upload upFiles = new Upload();
string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater, false, true);
//返回成功信息
context.Response.Write(msg);
context.Response.End();
}
#end
public class Upload {
/// <summary>
/// 文件上传方法C
/// </summary>
/// <param name="postedFile">文件流</param>
/// <param name="isThumbnail">是否生成缩略图</param>
/// <param name="isWater">是否打水印</param>
/// <param name="isReOriginal">是否返回文件原名称</param>
/// <returns>服务器文件路径</returns>
public string fileSaveAs(HttpPostedFile postedFile,bool isThumbnail,bool isWater,bool _isImage,bool _isReOriginal) {
try {
string fileExt = GetFileExt(postedFile.FileName); //文件扩展名,不含“.”
string originalFileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得文件原名
//string fileName = GetRamCode() + "." + fileExt; //随机文件名
if(originalFileName.Contains(",") || originalFileName.Contains(",")) //去掉文件名中的,和,
{
originalFileName = originalFileName.Replace(",","").Replace(",","");
}
string fileName = originalFileName;
string dirPath = GetUpLoadPath(); //上传目录相对路径
//检查文件扩展名是否合法
if(!CheckFileExt(fileExt)) {
return "{\"msg\": 0, \"msgbox\": \"不允许上传" + fileExt + "类型的文件!\"}";
}
//检查是否必须上传图片
if(_isImage && !IsImage(fileExt)) {
return "{\"msg\": 0, \"msgbox\": \"对不起,仅允许上传图片文件!\"}";
}
//检查文件大小是否合法
if(!CheckFileSize(fileExt,postedFile.ContentLength)) {
return "{\"msg\": 0, \"msgbox\": \"文件超过限制的大小啦!\"}";
}
//获得要保存的文件路径
string serverFileName = dirPath + fileName;
string serverThumbnailFileName = dirPath + "small_" + fileName;
string returnFileName = serverFileName;
//物理完整路径
string toFileFullPath = GetMapPath(dirPath);
//检查有该路径是否就创建
if(!Directory.Exists(toFileFullPath)) {
Directory.CreateDirectory(toFileFullPath);
}
//保存文件
//判断文件是否存在,存在在后面名字追加1
string newpath = GetNewPathForDupes(toFileFullPath + fileName);
postedFile.SaveAs(newpath);
long FactSize = postedFile.ContentLength;
string m_strSize = "";
if(FactSize < 1024.00)
m_strSize = FactSize.ToString("F2") + " Byte";
else if(FactSize >= 1024.00 && FactSize < 1048576)
m_strSize = (FactSize / 1024.00).ToString("F2") + " K";
else if(FactSize >= 1048576 && FactSize < 1073741824)
m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";
else if(FactSize >= 1073741824)
m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";
string tmpFilename = dirPath + Path.GetFileName(newpath);
//如果需要返回原文件名
if(_isReOriginal) {
return "{\"msg\": 1, \"msgbox\": \"" + tmpFilename + "\", \"mstitle\": \"" + originalFileName + "\",\"mssite\":\"" + m_strSize + "\"}";
}
return "{\"msg\": 1, \"msgbox\": \"" + tmpFilename + "\",\"mssite\":\"" + m_strSize + "\"}";
} catch {
return "{\"msg\": 0, \"msgbox\": \"上传过程中发生意外错误!\"}";
}
}
#region 获得当前绝对路径
/// <summary>
/// 返回文件扩展名,不含“.”
/// </summary>
/// <param name="_filepath">文件全名称</param>
/// <returns>string</returns>
public static string GetFileExt(string _filepath) {
if(string.IsNullOrEmpty(_filepath)) {
return "";
}
if(_filepath.LastIndexOf(".") > 0) {
return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.”
}
return "";
}
/// <summary>
/// 生成日期随机码
/// </summary>
/// <returns></returns>
public static string GetRamCode( ) {
#region
return DateTime.Now.ToString("yyyyMMddHHmmssffff");
#endregion
}
/// <summary>
/// 获得当前绝对路径
/// </summary>
/// <param name="strPath">指定的路径</param>
/// <returns>绝对路径</returns>
public static string GetMapPath(string strPath) {
if(strPath.ToLower().StartsWith("http://")) {
return strPath;
}
if(HttpContext.Current != null) {
return HttpContext.Current.Server.MapPath(strPath);
} else //非web程序引用
{
strPath = strPath.Replace("/","\\");
if(strPath.StartsWith("\\")) {
strPath = strPath.Substring(strPath.IndexOf('\\',1)).TrimStart('\\');
}
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,strPath);
}
}
#endregion
/// <summary>
/// 返回上传目录相对路径
/// </summary>
/// <param name="fileName">上传文件名</param>
private string GetUpLoadPath( ) {
string path = "/attach_upload/"; //站点目录+上传目录
switch(2) {
case 1: //按年月日每天一个文件夹
path += DateTime.Now.ToString("yyyyMMdd");
break;
default: //按年月/日存入不同的文件夹
path += DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");
break;
}
return path + "/";
}
/// <summary>
/// 是否为图片文件
/// </summary>
/// <param name="_fileExt">文件扩展名,不含“.”</param>
private bool IsImage(string _fileExt) {
ArrayList al = new ArrayList();
al.Add("bmp");
al.Add("jpeg");
al.Add("jpg");
al.Add("gif");
al.Add("png");
if(al.Contains(_fileExt.ToLower())) {
return true;
}
return false;
}
/// <summary>
/// 检查是否为合法的上传文件
/// </summary>
private bool CheckFileExt(string _fileExt) {
//检查危险文件
string[] excExt = { "asp","aspx","php","jsp","htm","html" };
for(int i = 0;i < excExt.Length;i++) {
if(excExt[i].ToLower() == _fileExt.ToLower()) {
return false;
}
}
//检查合法文件 限制上传文件 王景波 2012.06
//string[] allowExt = this.siteConfig.attachextension.Split(',');
//for (int i = 0; i < allowExt.Length; i++)
//{
// if (allowExt[i].ToLower() == _fileExt.ToLower())
// {
// return true;
// }
//}
return true;
}
/// <summary>
/// 检查文件大小是否合法
/// </summary>
/// <param name="_fileExt">文件扩展名,不含“.”</param>
/// <param name="_fileSize">文件大小(KB)</param>
private bool CheckFileSize(string _fileExt,int _fileSize) {
判断是否为图片文件
//if (IsImage(_fileExt))
//{
// if (10240 > 0 && _fileSize > this.siteConfig.attachimgsize * 1024)
// {
// return false;
// }
//}
//else
//{
// if (this.siteConfig.attachfilesize > 0 && _fileSize > this.siteConfig.attachfilesize * 1024)
// {
// return false;
// }
//}
return true;
}
private string GetNewPathForDupes(string path) {
string directory = Path.GetDirectoryName(path);
string filename = Path.GetFileNameWithoutExtension(path);
if(filename.Contains(",") || filename.Contains(",")) {
filename = filename.Replace(",","").Replace(",","");
}
string extension = Path.GetExtension(path);
int counter = 1;
string newFullPath;
do {
string newFilename = string.Format("{0}({1}){2}",filename,counter,extension);
newFullPath = Path.Combine(directory,newFilename);
counter++;
} while(System.IO.File.Exists(newFullPath));
return newFullPath;
}
}