1. 程式人生 > >WebService 上傳圖片

WebService 上傳圖片

//pathand 為儲存路徑
//filename  為儲存資料夾名`這裡寫程式碼片`
   [WebMethod(Description = "上傳圖片")]
        public bool UpdateFile(byte[] content, string pathand, string filename)
        {
            string pathandname = pathand + filename;
            int index = pathandname.LastIndexOf(".");
            if (index == 0
) { return false; } else { string extended = string.Empty; if (index + 1 == pathandname.Length) { return false; } else { extended = pathandname.Substring(index + 1
); if (extended == "jpeg" || extended == "gif" || extended == "jpg" || extended == "bmp" || extended == "png") { try { if (!Directory.Exists(@pathand))//若資料夾不存在則新建資料夾
{ Directory.CreateDirectory(@pathand); //新建資料夾 } //File.WriteAllBytes(Server.MapPath(pathandname), content); File.WriteAllBytes(pathandname, content); return true; } catch (Exception ex) { return false; } } else { return false; } } } }

呼叫端程式碼

“` Boolean fileOK = false; string path = Server.MapPath(“~/resources/images/address”); if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path);//不存在目錄則建立目錄 } string newFileName = FileUpload_pic.FileName; if (this.FileUpload_pic.HasFile) { string fileExtension = System.IO.Path.GetExtension(FileUpload_pic.FileName).ToLower();

            if (fileExtension.Equals(".jpg") || fileExtension.Equals(".png") || fileExtension.Equals("gif"))
            {
                fileOK = true;
            }
        }
        WebReference.CoreServiceV2 web = new WebReference.CoreServiceV2();

        if (!fileOK)
        {
            JavaScript.Alert("請檢查檔案格式,只能上傳圖片(*.jpg、*.png或*.gif格式)!");
            return;
        }
        try
        {
            if (Directory.Exists(Server.MapPath("~/resources/images/address")) == false)//如果不存在就建立file資料夾
            {
                Directory.CreateDirectory(Server.MapPath("~/resources/images/address"));
            }

            // FileUpload_pic.PostedFile.SaveAs(path + newFileName);
            var str = Server.MapPath("~/resources/images/address/");
            //將源地址的圖片copy到目標地址
            FileStream fs = new FileStream(FileUpload_pic.PostedFile.FileName, FileMode.Open, FileAccess.Read);
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            if (web.UpdateFile(bytes, str, FileUpload_pic.FileName))
            {
                JavaScript.Alert("成功");
            }
            }
            catch (Exception ex)
        {
            JavaScript.Alert("圖片上傳失敗:" + ex.Message);
            return;
        }```
   [參考連結](https://www.cnblogs.com/qq260250932/p/4965982.html)     程式碼展示