【c#】上傳圖片(包含ajax上傳圖片)


1、拖拽上傳圖片

1.1、后台代碼中修改窗體屬性,添加 AllowDrop = true 

1.2、給窗體添加拖拽事件,在事件列表找到拖拽 雙擊即可:

DragDrop 生成的方法中添加代碼如下:

 private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Move;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

在 DragEnter 方法中添加代碼如下: 

private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            //判斷
            string[] files = e.Data.GetData(DataFormats.FileDrop) as string[];
            string file = files[0];
            if (!file.ToLower().EndsWith(".png") && !file.ToLower().EndsWith(".jpg"))
            {
                MessageBox.Show("需要圖片文件!");
                return;
            }
            //PictureBox控件顯示圖片
            Image.Load(file);
        }

2、點擊按鈕上傳圖片

2.1、官方文檔地址:https://msdn.microsoft.com/zh-cn/library/system.windows.controls.openfiledialog.filter(v=VS.95).aspx
2.2、在窗體中添加控件 OpenFileDialog ,提供了提示用戶打開文件的功能。按鈕添加代碼如下:
 private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //PictureBox控件顯示圖片
                Image.Load(openFileDialog.FileName);
            }
        }
2.3、上傳圖片並保存
private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //PictureBox控件顯示圖片
                Image.Load(openFileDialog.FileName);
                //獲取用戶選擇文件的后綴名 
                string extension = Path.GetExtension(openFileDialog.FileName);
                //聲明允許的后綴名 
                string[] str = new string[] { ".gif", ".jpge", ".jpg", ".png" };
                if (!str.Contains(extension))
                {
                    MessageBox.Show("僅能上傳gif,jpge,jpg格式的圖片!");
                }
                else
                {
                    //獲取用戶選擇的文件,並判斷文件大小不能超過20K,fileInfo.Length是以字節為單位的 
                    FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
                    if (fileInfo.Length > 20480)
                    {
                        MessageBox.Show("上傳的圖片不能大於20K");
                    }
                    else
                    {
                        //絕對路徑
                        string image = openFileDialog.FileName;
                        //  是指XXX.jpg
                        string picpath = openFileDialog.SafeFileName;
                        File.Copy(openFileDialog.FileName, Application.StartupPath + "\\Image\\" + picpath);
                    }
                }
            }
        }

 MVC上傳圖片

HTML代碼

 <input name="Userfile" id="Userfile" type="file"></span>

Js代碼

var formDate = new FormData();
var files = $("#Userfile").get(0).files;
//拼接請求參數
formDate.append("Userfile", files[0]);
//如果有其他參需要一起提交到后台
formDate.append("location", location);
 $.ajax({
            type: "POST",
            url: url,
            contentType: false,
            cache: false,
            processData: false,           
            data: formDate,
            error: function (request) {
               
            },
            success: function (data) {
               
            }
        });

Web API后端代碼

  [HttpPost]
  public string Save()
  {
        //圖片存儲路徑
        string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "img/";
         //用戶提交的數據
          var Data = System.Web.HttpContext.Current.Request.Form;
          string filesrc = string.Empty;
          string src = string.Empty;
          //獲取上傳的文件
          var httpPostedFile = HttpContext.Current.Request.Files;
          if (httpPostedFile != null && httpPostedFile.Count > 0)
          {
                var file = httpPostedFile[0];
                string imgType = Path.GetExtension(file.FileName);
                //限制文件上傳類型
                if (imgType.Contains(".jpg") || imgType.Contains(".png") || imgType.Contains(".bmp"))
                {
                    string FileName = Guid.NewGuid().ToString() + imgType;
                    filesrc = path + FileName;
                    src = "/images/" + FileName;
                    // 如果目錄不存在則要先創建
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    file.SaveAs(filesrc);

                }
            }
            if (!string.IsNullOrEmpty(src))
            {
                //存儲圖片路徑到數據庫
            }
            return "上傳成功后的圖片地址";
 }

Mvc端上傳代碼

        /// <summary>
        /// 圖片上傳
        /// </summary>
        /// <returns></returns>
        public string UploadImage()
        {
            var file = Request.Files.Get("file");
            string uid = file.FileName;
            if (!uid.IsEmpty())//服務器是否存在該文件
            {
                return "未獲取到上傳的圖片文件信息";
            }
            if (file.ContentLength == 0)
            {

                return "文件不存在";
            }
            // 獲取上傳的圖片名稱和擴展名稱
            string fileFullName = Path.GetFileName(file.FileName);
            string fileExtName = Path.GetExtension(fileFullName);
            if (fileExtName.Contains(".jpg") || fileExtName.Contains(".png") || fileExtName.Contains(".bmp"))
            {
                return "文件類型錯誤";
            }
            //獲取當前項目所在的物流路徑
            string path = Request.PhysicalApplicationPath;
            var src = path + "/images/";

            // 如果目錄不存在則要先創建
            if (!Directory.Exists(src))
            {
                Directory.CreateDirectory(src);
            }
            file.SaveAs(src + fileFullName);
            return src + fileFullName;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM