.net MVC中 在视图中上传的附件图片怎么保存到数据库

2024-12-04 19:18:53
推荐回答(1个)
回答1:

图片保存到数据库不是最佳的选择.

你可以搜索一下Uploadify 插件. 这个插件非常好用
一般将图片存为图片文件.

大致代码如下:

$("#btn_upload_attachment").uploadify({
height: 25,
swf: '../Scripts/plugin/uplodify/uploadify.swf',
uploader: '/Home/Upload',
queueSizeLimit: 1,
formData: { ID: newId },
buttonText: '选择文件',
width: 80,
onUploadSuccess: function (file, data, response) {
eval("data=" + data);
AddToAttachmentList(data.Data);
}
});

后台代码处理:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Upload(HttpPostedFileBase fileData, Guid? ID)
{
if (fileData != null)
{
try
{
// 文件上传后的保存路径
var filePath = Path.Combine(ConfigurationManager.AppSettings["BusinessFiles"], Ticket.OrgId.ToString());
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
var fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
var fileExtension = Path.GetExtension(fileName); // 文件扩展名
var fileID = Guid.NewGuid();
var saveName = fileID.ToString() + fileExtension; // 保存文件名称

fileData.SaveAs(filePath + "/" + saveName);
// 作为临时附件存入附件表
var attachments = new Attachments();
attachments.ID = fileID;
attachments.OrgID = Ticket.OrgId;
attachments.BusinessType = (byte)BusinessType.TransferContract;
attachments.Status = (byte)AttachmentStatus.Temp;
if (ID.HasValue)
{
attachments.BusinessID = ID.Value;
}
attachments.Extension = fileExtension;
attachments.Name = fileName;
attachments.Size = fileData.ContentLength;
attachments.UploadTime = GetNow();
attachments.UploadBy = Ticket.EmployeeName;
attachments.UploadByID = Ticket.UserId;
AttachmentsBLL.SaveAttachment(attachments);
return Json(new { Success = true, FileName = fileName, SaveName = saveName, FileID = fileID, Data = attachments });
}
catch (Exception ex)
{
return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet);
}
}