C# 接收前端上傳圖片


//傳的是我用戶id(perid)
public static string UploadUid(int perid) {
	//path為你當前項目下的路徑,   perimage為存儲圖片的文件夾
	string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "perimage/";
	var fileNewName = "";
	// 如果目錄不存在則要先創建
	if (Directory.Exists(path)) {
		//string path = "D:\\freehost\\mxcjobcn\\web\\perimage/";
		//用戶提交的數據
		//var Data = System.Web.HttpContext.Current.Request.Form;
		string filesrc = "";
		//獲取上傳的文件
		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") || imgType.Contains(".jpeg") ||
				imgType.Contains(".gif")) {
				//返回給前端一個名字用來搜索圖片地址並展示
				fileNewName = perid + DateTime.Now.ToString("yyyyMMddHHmmss") + imgType;
				filesrc = path + fileNewName;
				file.SaveAs(filesrc);
			}
		}
	} else {
		string filesrc = "";
		//獲取上傳的文件
		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") || imgType.Contains(".jpeg") ||
				imgType.Contains(".gif")) {
				fileNewName = perid + DateTime.Now.ToString("yyyyMMddHHmmss") + imgType;
				filesrc = path + fileNewName;
				file.SaveAs(filesrc);
			}
		}
	}
	return fileNewName;
}


免責聲明!

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



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