[英]ASP.NET Web API upload image to SQL Server database
我正在使用圖像編寫文章API,並且一直在遵循本教程中有關在ASP.NET Web API中上傳文件的信息, Title
和Content
已按預期保存到數據庫中。
這里的問題是,我發布的圖像保存到本地文件夾中,但Filename
, Filepath
, Filelength
和Filecreatedtime
未保存到數據庫中。
使用郵遞員將文章發布到數據庫:
ImageFolder
:
GET
索引:
數據庫:
這是我的Article
模型:
namespace Wwf_Article.Models
{
using System;
using System.Collections.Generic;
public partial class Article
{
public int ID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
public float FileLength { get; set; }
public DateTime FileCreatedTime { get;
}
}
這是我的POST控制器
[Mime]
public async Task<IHttpActionResult> Post()
{
var fileuploadPath = HttpContext.Current.Server.MapPath("~/ImageFolder");
var multiFormDataStreamProvider = new MultiFileUploadProvider(fileuploadPath);
await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
string uploadingFileName = multiFormDataStreamProvider.FileData.Select(x => x.LocalFileName).FirstOrDefault();
Article article = new Article
{
Title = HttpContext.Current.Request.Form["Title"],
Content = HttpContext.Current.Request.Form["Content"],
//these four lines below aren't saved to DB
FilePath = uploadingFileName,
FileName = Path.GetFileName(uploadingFileName),
FileLength = new FileInfo(uploadingFileName).Length,
FileCreatedTime = DateTime.Now
};
db.Articles.Add(article);
db.SaveChanges();
return Ok();
}
任何想法如何解決此問題?
您提到的以下4四行是Article模型類的一部分嗎? 我的意思是(FilePath,FileName,FileLength和FileCreatedTime)
1-如果是,我認為您可以使用存儲過程來實現您的請求,如下所示
CREATE PROC spInsertArticle
@Title varchar(100),
@Content varchar(100),
@FileName varchar(500),
@FilePath varchar(500),
@FileLength varchar(500)
AS
Insert Into ArticleTable(Title,Content,FileName,
FilePath,FileLength,FileContentTime)
Values (@Title,@Content,@FileName,
@FilePath,@FileLength,GetDate())
2-回到您的api項目並創建一個名為ArticleModel的模型類:
public class ArticleModel
{
public string Title {get; set; }
public string Content {get; set; }
public string FileName {get; set; }
public string FilePath {get; set; }
public string FileLength {get; set; }
}
3-在ArticleController中創建一個api post方法
[Route("api/ArticleController/PostArticle")]
public HttpResponseMessage PostArticle(ArticleModel obj)
{
if (ModelState.IsValid)
{
try
{
string PhotoPath = Convert.ToString(ConfigurationManager.AppSettings["ImagePath"]);
ArticleModel newObj = new ArticleModel();
newObj.Title = obj.Title ;
newObj.Content = obj.Content;
newObj.FileName = obj.FileName;
newObj.FilePath = obj.FilePath;
newObjl.FileLength = obj.FileLength;
if (String.IsNullOrEmpty(newObj.Content))
{
}
else
{
string startingFilePath = PhotoPath;
string FilePath = SaveImage(newObj.Content, startingFilePath, newObj.FileName);
FileInfo fInfo = new FileInfo(FilePath);
newObj.Content = fInfo.Name;
}
ArticleEntities context = new ArticleEntities();
var newArticle = context.spInsertArticle(newObj.Title, newObj.Content,
newObj.FileName, newObj.FilePath, newObj.FileLength);
return Request.CreateResponse(HttpStatusCode.Created, newArticle);
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
}
}
4-最后創建PostArticle方法中提到的SaveImage方法
private string SaveImage(string base64, string FilePath, string ImageName)
{
//Get the file type to save in
var FilePathWithExtension = "";
string localBase64 = "";
if (base64.Contains("data:image/jpeg;base64,"))
{
FilePathWithExtension = FilePath + ImageName + ".jpg";
localBase64 = base64.Replace("data:image/jpeg;base64,", "");
}
else if (base64.Contains("data:image/png;base64,"))
{
FilePathWithExtension = FilePath + ImageName + ".png";
localBase64 = base64.Replace("data:image/png;base64,", "");
}
else if (base64.Contains("data:image/bmp;base64"))
{
FilePathWithExtension = FilePath + ImageName + ".bmp";
localBase64 = base64.Replace("data:image/bmp;base64", "");
}
else if (base64.Contains("data:application/msword;base64,"))
{
FilePathWithExtension = FilePath + ImageName + ".doc";
localBase64 = base64.Replace("data:application/msword;base64,", "");
}
else if (base64.Contains("data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,"))
{
FilePathWithExtension = FilePath + ImageName + ".docx";
localBase64 = base64.Replace("data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,", "");
}
else if (base64.Contains("data:application/pdf;base64,"))
{
FilePathWithExtension = FilePath + ImageName + ".pdf";
localBase64 = base64.Replace("data:application/pdf;base64,", "");
}
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(localBase64)))
{
using (FileStream fs = new FileStream(FilePathWithExtension, FileMode.Create, FileAccess.Write))
{
//Create the specified directory if it does not exist
var photofolder = System.IO.Path.GetDirectoryName(FilePathWithExtension);
if (!Directory.Exists(photofolder))
{
Directory.CreateDirectory(photofolder);
}
ms.WriteTo(fs);
fs.Close();
ms.Close();
}
}
return FilePathWithExtension;
}
5,以郵遞員或招搖工具嘗試此操作,它將為您服務。 我可以進行任何討論
首先,創建一個通用接口倉庫類
public interface IRepository<T> where T : class
{
T GetById(int id);
void Add(T entity);
}
創建一個將實現接口的類
public class EFRepository<T> : IRepository<T> where T : class
{
public EFRepository(PayrollcshrnewEntities dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
protected ArticleEntities DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public virtual T GetById(int id)
{
return DbSet.Find(id);
}
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
}
由於某種原因,在刪除edmx並使用ADO重新創建EF設計器表之后,POST控制器開始工作。
事實證明edmx圖中缺少字段。
謝謝大家的幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.