Saving image to the filesystem using mvc3

2019-05-07 17:57发布

问题:

I have some simple entity which now needs to have a Profile image. What is the proper way to do this? So, it is 1 to 1 relationship, one image is related only to one entity and vice versa. This image should be uploaded through webform together with inserting related entity.

So, as I'm pointed to use filesystem to store image and to persisted only path image into db I have to ask if someone have any tutorial or link to provide, or code example.

Thanks

回答1:

The steps you should do to create an entity with an image.

  1. Create asp form with image upload and collect data for entity. Ideally if you do it in two steps, being the first one image upload.
  2. On submit post image (maybe you have to configure something for big images) and entity data
  3. Check image in backend. IF ok, store in a folder.
  4. If image is ok, create entity in DB. Entity image path should updated from data in step 3.

Some advices:

  • Code defensively.
  • On upload of image check that image is valid (even made a binary check of image header)
  • Wait until image is uploaded and checked to create entity.
  • Don't allow to overwrite an existing image in case of a INSERT of a new entity.
  • Name images as primary key (1.jpg, 2.jpg)
  • On load of image don't assume that image is going to be there.
  • Do not allow (if possible) manual interaction with images (No remoting in machine and copying images from one place to other). Manual interaction can cause inconsistencies.


回答2:

I persist the IMAGE source itself to the database using Entity Framework, and i makesure i inlcude the following in the database:

  • Created Date
  • File Type (Content Type)
  • Source (binary)
  • File Name
  • File Size
  • Height
  • Width

I load it using byte streams/BinaryReaders. My Code is here:

http://garfbradazweb.wordpress.com/2011/08/16/mvc-3-upload-sql-server-entity-framework/

The full tutorial series is here: http://garfbradazweb.wordpress.com/welcome-to-my-ancedotes/#

In terms of relationships, i have the following:

Media Table - Stores all the images and includes the above columns mentioned. You may need images related to other tables. The key is a uniquieid (SQL) for which the C# Type is Guid.

Profile Table - Stores my Profile of the user. Here i have a ImageId which is a ome-to-one relationship between the Profile row and the Image.

I have written a MVCImage app which shows you how to use this here:

http://mvcimage.codeplex.com/ Let me know if this is OK or if you need code examples.



回答3:

For a single image I would just store it directly in the table. You won't be inflating the database as you will be resizing the image to accepted size (ie. 128x128 px).

Also, no need to worry about file system backups and problems with multiple web servers.



回答4:

You can use the HTML input tag with a type of file:

<input type="file" name="file" />

A full MVC example can here found here.