<script src="../js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="../js/jquery-form.js" type="text/javascript"></script>
<form id="form1" method="post" action="">
<input id="ctlFilePath" name="FilePath" class="easyui-textbox" readonly="readonly" style="width:362px; display:none"/>
<input id="ctlUploadFile" name="UploadFile" class="UploadFileControl" file_type="1" type="file" accept="application/msword" style="width:362px;" />
</form>
function uploadFile(formObj) {
var uploadFileControl = $('#ctlUploadFile');
if (uploadFileControl) {
//判断是否选择文件
var value = uploadFileControl.val();
if (value == null || value == "") {
showError("请选择文件。");
uploadFileControl.focus();
uploadFileControl.select();
return false;
}
var isSuccessed = false;
var fileType = uploadFileControl.attr('file_type');
fileType = fileType || '';
$(formObj).ajaxSubmit({
async: false,
type: 'post',
url: "Upload.ashx?Method=UploadFile&FileType=" + fileType,
success: function (data) {
isSuccessed = data.isOk == '1' ? true : false;
if (isSuccessed) {
var filePath = data.message;
var filePathControl = $('#ctlFilePath');
if (filePathControl) {
filePathControl.val(filePath);
}
}
}
});
if (!isSuccessed) {
showError("上传文件失败。");
return false;
}
}
return true;
}
Upload.ashx:
public void ProcessRequest(HttpContext context)
{
string method = Request["Method"] ?? "";
if (!string.IsNullOrEmpty(method))
{
foreach (MethodInfo mi in this.GetType().GetMethods())
{
if (mi.Name.ToLower() == method.ToLower())
{
mi.Invoke(this, null);
break;
}
}
}
}
/// <summary>
/// 上传文件
/// </summary>
public void UploadFile()
{
try
{
int intFileType = 0;
int.TryParse(Request["FileType"], out intFileType);
bool blnIsSuccessed = false;
string strFilePath = "";
if (intFileType > 0)
{
string strPath = GetUploadFilePath(intFileType);
if (!string.IsNullOrEmpty(strPath))
{
Response.ContentType = "text/plain";
HttpFileCollection files = Request.Files;
if (files.Count > 0)
{
HttpPostedFile file = files[0];
string strFileFullName = file.FileName;
string strFileFormat = strFileFullName.Substring(strFileFullName.LastIndexOf("."));
strFilePath = string.Format("{0}/{1}.{2}", strPath, Guid.NewGuid().ToString(), strFileFormat);
file.SaveAs(Server.MapPath(strFilePath));
blnIsSuccessed = true;
}
}
}
WriteMessage(blnIsSuccessed ? 1 : 0, strFilePath);
}
catch (Exception ex)
{
WriteMessage(0, ex.Message);
}
}
/// <summary>
/// 获取上传文件路径
/// </summary>
/// <param name="Type"></param>
/// <returns></returns>
private string GetUploadFilePath(int FileType)
{
string strFooter = null;
switch (FileType)
{
case 1:
strFooter = "LegalWriter";
break;
case 2:
strFooter = "Photo";
break;
case 3:
strFooter = "Palmprint";
break;
}
if (string.IsNullOrEmpty(strFooter))
{
return null;
}
return string.Format("~/Jz_People_UploadFile/{0}", strFooter);
}
private WriteMessage(int Status, string Message)
{
string jsFormat = "\"isOk\":\"{0}\", \"message\":\"{1}\"";
Response.Write(string.Format(jsFormat , Status, Message));
}
浙公网安备 33010602011771号