.NET Framework 或 .NET Core 中实现图片上传功能的代码示例通常涉及前端HTML表单与后端C#控制器之间的交互,以及文件流处理和可能的存储逻辑。以下是一个基本的ASP.NET MVC或ASP.NET Core MVC控制器中的Action方法示例,用于接收并保存上传的图片到服务器的指定文件夹:
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
public class ImageController : Controller
{
private readonly IWebHostEnvironment _webHostEnvironment; // 依赖注入Web宿主环境服务
public ImageController(IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
}
[HttpPost]
public IActionResult UploadImage(IFormFile file)
{
if (file == null || file.Length == 0)
{
return Json(new { success = false, message = "请选择一个图片文件进行上传。" });
}
// 检查文件扩展名是否为允许的类型
string[] allowedExtensions = { ".jpg", ".jpeg", ".png", ".gif" }; // 更多类型可添加
string extension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (!allowedExtensions.Contains(extension))
{
return Json(new { success = false, message = "不支持的图片格式,请上传.jpg、.jpeg、.png或.gif格式的图片。" });
}
// 设置图片保存目录
string folderPath = Path.Combine(_webHostEnvironment.WebRootPath, "bookimg");
Directory.CreateDirectory(folderPath); // 如果文件夹不存在,则创建
// 生成唯一文件名(防止重名)
string uniqueFileName = Guid.NewGuid().ToString() + extension;
string filePath = Path.Combine(folderPath, uniqueFileName);
// 保存图片到服务器
using (var stream = new FileStream(filePath, FileMode.Create))
{
file.CopyTo(stream);
}
// 图片上传成功,返回相关信息
return Json(new { success = true, imageUrl = $"/bookimg/{uniqueFileName}" });
}
}
在前端,你需要有一个HTML表单或者使用Ajax提交来发送POST请求,并包含enctype="multipart/form-data"
属性以便能够上传文件:
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" accept=".jpg, .jpeg, .png, .gif" />
<button type="submit">上传图片</button>
</form>
<script>
$("#uploadForm").submit(function(event) {
event.preventDefault(); // 阻止默认表单提交行为
var formData = new FormData(this); // 创建FormData对象包含表单数据
$.ajax({
url: '/Image/UploadImage',
type: 'POST',
data: formData,
contentType: false, // 必须设置为false,jQuery才会正确发送FormData
processData: false, // 不允许jQuery对数据进行序列化处理
success: function(response) {
if (response.success) {
alert('图片上传成功');
// 更新图片显示路径等操作...
} else {
alert(response.message);
}
},
error: function(xhr, status, error) {
alert('上传失败:' + xhr.responseText);
}
});
});
</script>