C#使用HTML文件中的file文件上传,用C#代码接收上传文件
單獨做圖片上傳很簡單,如果要客戶端要上傳頭像保存到服務器就要稍微麻煩一點點了。
不多說了,直接上源碼:
private void Upload() ???????
{
??????????? string jsonInfo = string.Empty;
///這句是關鍵,它是獲取HTTP中文件流 的對象集合。
??????????? HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
??????????? string mobile = string.IsNullOrEmpty(Request.Form["mobile"]) ? Request.QueryString["mobile"] : Request.Form["mobile"];
??????????? string fName = "";
??????????? // string.IsNullOrEmpty(Request.Form["filename"]) ? Request.QueryString["filename"] : Request.Form["filename"];
??????????? string status = string.Empty;
??????????? string error = string.Empty;
///在這里我們只取其中一個上傳對象操作
???????????? fName = hfc[0].FileName;
??????????? try
??????????? {
??????????????? string[] list;
??????????????? if (!string.IsNullOrEmpty(fName))
??????????????? {
??????????????????? list = fName.Split('.');
??????????????????? if (list.Length > 1)
??????????????????? {
??????????????????????? string ftype = list[1].ToLower();
??????????????????????? if (ftype == "jpg" || ftype == "png" || ftype == "jpeg")
??????????????????????? {
??????????????????????????? fName = mobile + "." + list[1];
??????????????????????????? string filePath = "../CSS/headmiages/";
??????????????????????????? hfc[0].SaveAs(System.IO.Path.Combine(MapPath(filePath), fName));
??????????????????????????? RockUserInfo userInfo = new RockUserInfo();
??????????????????????????? userInfo.LogOnPhoneNum = mobile;
??????????????????????????? //根據手機號查詢出用戶基本信息
??????????????????????????? userInfo = SearchByPhone(userInfo);
??????????????????????????? userInfo.filename = fName;
??????????????????????????? //插入頭像信息保存
??????????????????????????? Save(userInfo);
??????????????????????????? status = "0";
??????????????????????????? error = "";
??????????????????????? }
??????????????????????? else
??????????????????????? {
??????????????????????????? status = "1";
??????????????????????????? error = "請上傳 .jpg/.png/.jpeg/類型的圖片";
??????????????????????? }
??????????????????? }
??????????????? }
??????????????? else
??????????????? {
??????????????????? status = "1";
??????????????????? error = "請上傳 .jpg/.png/.jpeg/類型的圖片";
??????????????? }
??????????????? //fileload.in
??????????? }
??????????? catch (Exception ex)
??????????? {
??????????????? status = "2";
??????????????? error = ex.ToString();
??????????? }
??????????? jsonInfo = "{\"" + "status" + "\":\"" + status + "\"," + "msg" + "\":\"" + error + "}";
??????????? Response.Write(jsonInfo);
??????? }
這樣就 OK了,在服務器端保存上傳文件,操作數據庫就基本達到目標了。很簡單吧!
這段代碼經過測試是沒有問題的,如果有不合理之處還望大家指出來共同進步。
轉載于:https://www.cnblogs.com/miao817/p/3607452.html
總結
以上是生活随笔為你收集整理的C#使用HTML文件中的file文件上传,用C#代码接收上传文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 学习操作小计
- 下一篇: asp.net(C#)写SQL语句技巧