1. 程式人生 > 其它 >小程式實現上傳圖片

小程式實現上傳圖片

技術標籤:c#小程式

c# 小程式上傳圖片,後臺程式碼

/// <summary>
/// 上傳圖片
/// </summary>
/// <returns>path 預設路徑 /Resource/WeChatFile </returns>
public ResultModel Pic()
{
   try
   {
       string path = HttpContext.Current.Request["path"];
       if (string.IsNullOrEmpty(path))
       {
           path =
"/upload/MiniApp/"; } HttpFileCollection files = HttpContext.Current.Request.Files; List<string> pathList = new List<string>(); foreach (string key in files.AllKeys) { HttpPostedFile file = files[key];//file.ContentLength檔案長度 if
(file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) { return Error("上傳檔案失敗,檔案不存在!"); } else { #region 儲存圖片 string FathName = Guid.NewGuid().ToString("N"); string FileEextension =
Path.GetExtension(files[0].FileName); string virtualPath = string.Format("{0}/{1}", path, FathName + FileEextension); string virtualPath_1 = string.Format("{0}/{1}", path, FathName + "_1" + FileEextension); string fullFileName = HttpContext.Current.Server.MapPath("~" + virtualPath); string fullFileName_1 = HttpContext.Current.Server.MapPath("~" + virtualPath_1); //建立資料夾,儲存檔案 var filePath = Path.GetDirectoryName(fullFileName); Directory.CreateDirectory(filePath); file.SaveAs(fullFileName_1); //壓縮圖片 if (file.ContentLength > (90 * 1024)) { Image img = new Bitmap(fullFileName_1); ImageHelper.GetPicThumbnail(fullFileName_1, fullFileName, img.Height, img.Width, 10); img.Dispose(); } else { file.SaveAs(fullFileName); } #endregion pathList.Add(virtualPath); } } return Success("檔案上傳成功", pathList); } catch (Exception ex) { return Error("上傳檔案失敗," + ex.Message); } }

操作結果返回類 ResultModel


    /// <summary>
    /// 操作結果 
    /// </summary>
    public class ResultModel
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool IsSucceed { get; set; }

        /// <summary>
        /// 操作結果型別
        /// </summary>
        public ResultType type { get; set; }

        /// <summary>
        /// 錯誤編碼
        /// </summary>
        public int errorcode { get; set; }

        /// <summary>
        /// 訊息內容
        /// </summary>
        public string message { get; set; }

        /// <summary>
        /// 返回資料
        /// </summary>
        public object resultdata { get; set; }

        /// <summary>
        /// 操作時間
        /// </summary>
        public DateTime time { get; set; }


    }
    /// <summary>
    /// 表示 ajax 操作結果型別的列舉
    /// </summary>
    public enum ResultType
    {
        /// <summary>
        /// 訊息結果型別
        /// </summary>
        info = 0,

        /// <summary>
        /// 成功結果型別
        /// </summary>
        success = 1,

        /// <summary>
        /// 警告結果型別
        /// </summary>
        warning = 2,

        /// <summary>
        /// 異常結果型別
        /// </summary>
        error = 3
    }