In MVC4, how to upload a file (image) to SQL Server, which is part of my domain model?

I'm relatively new to MVC, and I never had to deal with uploading a file (in particular, an image) to a SQL Server database. Honestly, I don't know what I'm doing here.

Here is what I have so far - here is my domain model (pay attention to HttpPostedFileBasein my model - this is what I want to download):

public class Profile
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage="Years of service is required")]
    [DisplayName("Years Service:")]
    public int YearsService { get; set; }

    [DataType(DataType.MultilineText)]
    [DisplayName("Notable Achivements:")]
    public string NotableAchivements { get; set; }

    [Required(ErrorMessage = "Technical skills are required")]
    [DataType(DataType.MultilineText)]
    [DisplayName("Technical Skills:")]
    public string TechnicalSkills { get; set; }

    [DisplayName("Upload Image: ")]
    public HttpPostedFileBase Photo { get; set; }

    public string CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
}

And here is my view:

@using (Html.BeginForm("Create", "Profiles", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
    @Html.LabelFor(model => model.YearsService)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.YearsService)
    @Html.ValidationMessageFor(model => model.YearsService)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.NotableAchivements)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.NotableAchivements)
    @Html.ValidationMessageFor(model => model.NotableAchivements)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.TechnicalSkills)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.TechnicalSkills)
    @Html.ValidationMessageFor(model => model.TechnicalSkills)
</div>

<input type="file" name="photo" />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}

I hope that there is something obvious that I am doing wrong. Can someone give some advice on how to upload a simple file to a SQL Server database?

+5
source share
3 answers

, . "", , "" MSSQL. . , , , AR-15, , .

, : . .

- . , . , . , , , , .

, Profile. - ProfileViewModel ProfileVM. Profile, . , , , SelectList DropDownListFor, , ViewBag .

. - :

public string Photo { get; set; }
public HttpPostedFileBase PhotoUpload { get; set; }

/ PhotoUpload, ( Photo , ).

@Html.TextBoxFor(m => m.PhotoUpload, new { type = "file" })

, :

if (model.PhotoUpload.ContentLength > 0) {
    // A file was uploaded
    var fileName = Path.GetFileName(model.PhotoUpload.FileName);
    var path = Path.Combine(Server.MapPath(uploadPath), fileName);
    model.PhotoUpload.SaveAs(path);
    model.Photo = uploadPath + fileName;
}

uploadPath , , - ~/uploads/profile/photos. , , , , ( , , ).

- . , - AutoMapper . automapper ( model ProfileViewModel):

var profile = AutoMapper.Mapper.Map<Profile>(model);

, - , , , :

var profile = db.Profiles.Find(userId);
...
Automapper.Mapper.Map(model, profile);

PhotoUpload, Photo. , Photo , , , , - .

, , , , , , , - , Word. if (ModelState.IsValid) :

var validTypes = new[] { "image/jpeg", "image/pjpeg", "image/png", "image/gif" };
if (!validTypes.Contains(model.PhotoUpload.ContentType))
{
    ModelState.AddModelError("PhotoUpload", "Please upload either a JPG, GIF, or PNG image.");
}

mime , -.

+8

, this this .

, Photo byte [] , ( , - LINQ to SQL Entity Framework).

, :

  • HttpPostedFileBase "" ( , "" )
  • , , MemoryStream InputStream HttpPostedFileBase
  • MemoryStream [] ToArray()
  • [] , .

, MemoryStream,

, , : -)

,

+2

In my application, sotre image is like base64string, therefore nvarchar (max) is the data type that I used. This means that you can transfer a base64String image in a JSON object from or to a website.

To convert an image to base64string

public static string ToBased64String(this Image image, ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();
    string based64String = Convert.ToBased64String(imageBytes);
    return based64String;

  }
}

then you can call your method as follows

image.ToBased64String

Convert base64String to image

public static ImageFromBased64String(string based64Image, string path)
{
  Image image = null;
  var bytes = Convert.FromBased64String(based64String);
  using (var fileStream = new FileStream(path, FileMode.Create))
  {
    fileStream.Write(bytes, 0, bytes.Length);
    fileStream.Flush();
    image = Image.FromStream(fileStream, true);
    return image;
  }
}

see my answer here

fooobar.com/questions/1149700 / ...

0
source

All Articles