ASP.NET Web API загрузить изображение в базу данных SQL Server - PullRequest
0 голосов
/ 01 октября 2018

Я пишу статью API с изображением, и я следую этому учебнику о загрузке файла в веб-API ASP.NET, Title и Content сохраняются в базе данных, как и предполагалось.

Проблема здесь в том, что изображения, которые я публикую, сохраняются в моей локальной папке, но поля Filename, Filepath, Filelength и Filecreatedtime не сохраняются в базе данных.

Отправка статьи в базу данных с почтальоном:

posting article to database

ImageFolder:

imageFolder

GET индекс:

get index

База данных:

article database

вот моя 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();
}

Любая идея, как исправитьэта проблема?

Ответы [ 5 ]

0 голосов
/ 01 октября 2018

По какой-то причине после того, как я удалил edmx и заново создал таблицу конструктора EF с помощью ADO, контроллер POST работает.

Оказывается, на диаграмме edmx отсутствуют поля.

Спасибо завсе равно помощь, ребята

0 голосов
/ 01 октября 2018

Создайте класс, который будет реализовывать интерфейс

        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);
                       }
              }
          }
0 голосов
/ 01 октября 2018

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-Создайте метод api post в ArticleController

  [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-И, наконец, создайте метод SaveImage, упомянутый в методе PostArticle

    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-Попробуйте это в Почтальоне или чванстве, и это будет работать для вас.Я доступен для любого обсуждения

0 голосов
/ 01 октября 2018

Прежде всего, создайте универсальный интерфейс репо класса

   public interface IRepository<T> where T : class
   {
        T GetById(int id);
        void Add(T entity);
   }
0 голосов
/ 01 октября 2018

4 строки ниже, как вы упомянули, часть вашего класса модели Article?Я имею в виду (FilePath, FileName, FileLength и FileCreatedTime)

...