Skip to content

Instantly share code, notes, and snippets.

@donma
Last active July 2, 2018 09:06
Show Gist options
  • Save donma/bbb60fc37c81fa8d2b00c4bf07526f05 to your computer and use it in GitHub Desktop.
Save donma/bbb60fc37c81fa8d2b00c4bf07526f05 to your computer and use it in GitHub Desktop.
Editor.Md - upload image using asp.net
using System;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
namespace MDEditorUploadImage
{
public class uploadimage : IHttpHandler
{
public class ResultInfo
{
public int success { get; set; }
public string message { get; set; }
public string url { get; set; }
}
public void ProcessRequest(HttpContext context)
{
try
{
//儲存路徑
DirectoryInfo FileDir = new DirectoryInfo(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "source\\");
//如果檔案夾沒有建立則自行建立
if (FileDir.Exists == false)
{
FileDir.Create();
}
HttpFileCollection uploadedFiles = context.Request.Files;
if (uploadedFiles.Count > 0)
{
HttpPostedFile userPostedFile = uploadedFiles[0];
if (userPostedFile.ContentLength > 0)
{
userPostedFile.SaveAs(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "source" + Path.DirectorySeparatorChar + Path.GetFileName(userPostedFile.FileName));
context.Response.Write(new JavaScriptSerializer().Serialize(new ResultInfo { message = "上傳成功", success = 1, url = "http://"+context.Request.Url.Authority + "/source/" + Path.GetFileName(userPostedFile.FileName) }));
}
}
}
catch (Exception ex)
{
context.Response.Write(new JavaScriptSerializer().Serialize(new ResultInfo { message = "上傳失敗:"+ex.Message, success = 0, url ="" }));
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment