.net MVC 簡單圖片上傳

主要完成的是在網頁上 上傳一張圖片到服務器服務器

我搜出來的上傳文件代碼都特別複雜,對於初學者來講,先解決能上傳的問題才最重要,並不須要特別多的功能,僅適合不會上傳的初學者,大神請繞路,錯誤請指出,謝謝post

view內容因爲是從項目中直接拷貝出來的,須要整理纔可以使用,看關鍵的就行了):spa

  圖片:code

  代碼:orm

            <!--這裏的method 和 enctype 要照寫,不要忘寫或寫錯-->
      <form action="ManageIcon" method="post" enctype="multipart/form-data" class="form-horizontal" role="form"> <div class="col-sm-6"> <label class="text-warning">請選擇尺寸爲160*160的圖片</label> <div class="row"> <div class="col-md-10"> <a href="#" class="thumbnail"> @*<img src="@ViewBag.LoginedUser.Icon" class="img-responsive" alt="Cinque Terre" style="height:160px;width:160px">*@ </a> </div> </div> </div> <div class="col-sm-6">
              <!--注意這裏,這裏的input在後臺很關鍵,下面會有提示--> <input name="filename" id="filename" type="file"/> </div> <div class="col-sm-12" style="margin-top:30px"> <button type="submit" id="s" class="btn btn-primary" style="margin-left:30px">保存</button> <button type="button" class="btn btn-default" style="margin-left:30px">取消</button> </div> </form>

項目目錄:blog

控制器代碼圖片

  [HttpPost]
        public ActionResult ManageIcon(IEnumerable <HttpPostedFileBase>filename)
        {
            foreach (var file in filename)
            {
          //重命名,圖片在服務器上的名字
string name = Path.GetFileName(file.FileName); string[] la = name.Split('.'); string nameNew = DateTime.Now.ToFileTimeUtc().ToString(); nameNew += "."+la[la.Length];

          //獲取項目根目錄 string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
          //這裏獲取前臺傳來的流信息
          
using (Stream inputstream = file.InputStream) { //在服務上建立文件流,事先已經在根目錄建立了\Images\Icons文件夾
            FileStream fs
= new FileStream(path+"Images\\Icons\\"+nameNew,FileMode.CreateNew,FileAccess.ReadWrite);   
            //文件讀寫
            byte[] buffer=new byte[1024];    int a = inputstream.Read(buffer,0,buffer.Length); while(a!=0){ fs.Write(buffer,0,buffer.Length); a = inputstream.Read(buffer, 0, buffer.Length); }

            //不寫這裏可能會上傳不完整,以下圖 fs.Flush(); fs.Close(); } }
return View(); }

 示例圖(第二張沒有上傳完整):ip

相關文章
相關標籤/搜索