IT

업로드 된 이미지, SQL 데이터베이스 또는 디스크 파일 시스템을 저장하기에 가장 좋은 장소는 무엇입니까?

lottoking 2020. 6. 28. 18:00
반응형

업로드 된 이미지, SQL 데이터베이스 또는 디스크 파일 시스템을 저장하기에 가장 좋은 장소는 무엇입니까?


사용자가 서버에 이미지를 업로드 할 수있는 응용 프로그램을 작성 중입니다. 나는 모든 JPEG를 하루에 약 20 장의 이미지를 기대하며 아마도 편집 / 크기 조정되지 않을 것입니다. (이것은 또 다른 질문입니다. 저장하기 전에 서버 측에서 이미지 크기를 조정하는 방법입니다. 누군가 주석에 .NET 리소스를 넣을 수 있습니다.) 업로드 된 이미지를 저장하기에 가장 좋은 장소가 무엇인지 궁금합니다.

  • 이미지를 파일 시스템에 파일로 저장하고 해당 이미지의 정확한 경로가있는 테이블에 레코드를 작성하십시오.

  • 또는 데이터베이스 서버의 "image"또는 "binary data"데이터 유형을 사용하여 이미지 자체를 테이블에 저장하십시오.

두 가지 장점과 단점이 있습니다. a) 파일을 쉽게 재배치 할 수 있고 테이블 항목을 변경해야하기 때문에 a)가 좋습니다. 반면에 나는 비즈니스 데이터를 웹 서버에 저장하는 것을 좋아하지 않으며 웹 서버를 비즈니스 데이터를 보유하고있는 다른 데이터 소스에 연결하고 싶지 않습니다 (보안상의 이유로) b) 모든 정보는 한 곳에서 쉽게 쿼리를 통해 액세스 할 수 있습니다. 반면에 데이터베이스는 매우 빨리 커질 것입니다. 데이터 아웃소싱이 더 어려울 수 있습니다.


나는 예외가 있지만 파일 시스템에 파일을 저장합니다. 파일의 경우 파일 시스템이 가장 유연하고 성능이 뛰어난 솔루션입니다 (보통).

데이터베이스에 파일을 저장하는 데 약간의 문제가 있습니다. 파일은 일반적으로 평균 행보다 훨씬 큽니다. 많은 큰 파일을 포함하는 결과 집합은 많은 메모리를 소비합니다. 또한 쓰기에 테이블 잠금 (예 : ISAM)을 사용하는 스토리지 엔진을 사용하는 경우 파일 테이블은 저장하는 파일의 크기 / 속도에 따라 자주 잠길 수 있습니다.

보안 관련-일반적으로 파일을 문서 루트 외부에있는 디렉토리 (http 요청을 통해 액세스 할 수 없음)에 저장하고 적절한 권한을 먼저 확인하는 스크립트를 통해 파일을 제공합니다.


옵션 B의 유일한 이점은 모든 데이터를 하나의 시스템에 저장하는 것입니다. 그러나 잘못된 이점입니다! 코드가 데이터 형식이므로 데이터베이스에 저장할 수도 있습니다. 어떻게 하시겠습니까?

특별한 경우가 없다면 :

  • 비즈니스 로직은 코드에 속합니다.
  • 구조화 된 데이터는 데이터베이스 (관계형 또는 비 관계형)에 속합니다.
  • 벌크 데이터는 스토리지 (파일 시스템 또는 기타)에 속합니다.

파일, 코드, 데이터

파일 시스템을 사용하여 파일을 유지할 필요는 없습니다. 대신 클라우드 스토리지 (예 : Amazon S3 ) 또는 인프라로서의 서비스 (예 : Uploadcare )를 사용할 수 있습니다.

https://uploadcare.com/upload-api-cloud-storage-and-cdn/

그러나 데이터베이스에 파일을 저장하는 것은 나쁜 생각입니다.


Flickr는 파일 시스템을 사용합니다. 여기에서 그 이유를 설명 합니다.


우리는 고객이 옵션 B (데이터베이스 저장) 몇 가지 다른 백엔드에 몇 번 주장했다 있고, 우리는 항상 결국 옵션 A (파일 시스템 스토리지)에 다시가는 끝났다.

이와 같은 대형 BLOB는 우리가 시도한 최신 버전 인 SQL Server 2005에서도 제대로 처리되지 않았습니다.

특히, 우리는 심각한 팽창을 보았고 아마도 잠금 문제가 있다고 생각합니다.

또 다른 참고 사항 : NTFS 기반 저장소 (Windows 서버 등)를 사용하는 경우 한 디렉토리에 수천 및 수천 개의 파일을 넣는 방법을 찾는 것이 좋습니다. 왜 그런지 잘 모르겠지만 때로는 파일 시스템이 그 상황에 잘 대처하지 못합니다. 누구든지 이것에 대해 더 많이 알고 있다면 듣고 싶습니다.

그러나 나는 항상 하위 디렉토리를 사용하여 조금 나눕니다. 작성 날짜는 종종 다음과 같이 잘 작동합니다.

이미지 /2008/12/17/.jpg

... 이것은 적절한 수준의 분리를 제공하고 디버깅하는 동안 약간 도움이됩니다. 탐색기와 FTP 클라이언트는 모두 엄청나게 큰 디렉토리가있을 때 약간 질식 할 수 있습니다.

편집 : 2017에 대한 간단한 참고 사항, 최신 버전의 SQL Server에는 내가 논의 한 단점을 피하기 위해 많은 BLOB를 처리하는 새로운 옵션이 있습니다.


최근에 PDF / Word 파일을 MySQL 테이블에 저장하는 PHP / MySQL 앱을 만들었습니다 (지금까지 파일 당 최대 40MB).

장점 :

  • 업로드 된 파일은 다른 모든 것과 함께 백업 서버에 복제되므로 별도의 백업 전략이 필요하지 않습니다 (안심하십시오).
  • 업로드 / 폴더가 없어도 모든 응용 프로그램이 어디에 있는지 알려주지 않기 때문에 웹 서버 설정이 약간 더 간단합니다.
  • 데이터 무결성을 향상시키기 위해 편집을 위해 트랜잭션을 사용하게됩니다. 고아 파일이 없거나 누락 된 것에 대해 걱정할 필요가 없습니다

단점 :

  • 테이블 중 하나에 500MB의 파일 데이터가 있으므로 mysqldump는 이제 looooong 시간이 걸립니다.
  • 파일 시스템과 비교할 때 전반적으로 메모리 / CPU 효율성이 떨어짐

구현을 성공이라고 부르고 백업 요구 사항을 처리하고 프로젝트 레이아웃을 단순화합니다. 앱을 사용하는 20-30 명의 사용자에게 성능이 좋습니다.


나는 이것이 오래된 게시물이라는 것을 알고 있습니다. 그러나이 페이지를 방문하는 많은 방문자는이 질문과 관련이 없습니다. 특히 초보자에게는.

웹 사이트에서 이미지 또는 파일을 업로드하고 저장하는 방법 :

정적 웹 사이트의 경우 일부 공유 호스팅의 파일 저장소가 여전히 적합하므로 문제가 없습니다. 동적 웹 사이트가 커지면 문제가 발생합니다. 데이터베이스에서 더 큰 것을 처리 할 수 ​​있지만 이미지와 같은 파일에서 더 큰 것이 문제가됩니다. 웹 사이트에는 두 가지 유형의 이미지가 있습니다.

  1. 이미지는 동적 블로그 관리자가 제공합니다. 일반적으로 이러한 이미지는 업로드 전에 최적화되었습니다.

  2. Images from users in case of users is allowed to upload images such as avatar. Or users can create blog content and put some images from text editor. This kind of images is difficult to predict the size. Users can upload big images just for small content by resize the view size but not resize the image size.

By ignoring item no. 1 above, quick solution for item no. 2 can be temporary solved by the following tips if we don't have image optimizer functionality in our website :

  1. Do not allow users to directly upload from text editor by redirecting them to image gallery. On this page users must upload file in advance before they can embedded in the content. This method is called as a File Manager.

  2. Use a crop image function for users to upload images. This will limit the image size even users upload very big file. The final image is the result of the cropped image. We can define the size in server side and accept only for example 500Kb or lower.

Now, that is only temporary. For final solution, the question is repeated :

  • How to handle a big images storage?
  • Resize or change the extension.
  • How a big or medium website or e-commerce handle the file storage for their images?

What we can do then :

  1. Migrate from share hosting VPS. Not enough? Then more higher by upgrading to Dedicated.

  2. Create your own server for file storage. Googling to do it. This is not as difficult as you think. Some people do it for their website.

  3. The easy way is use the CDN file storage service.

Okay, 1 and 2 is little bit expensive. But no 3 I think is the best solution.

Some CDN services allow you to store as many web files as you want.

Question, "how to upload file to CDN from our website?"

Don't worry, once you register, usually free, you will get guidance how to upload file and get their link from/to your website. You will get an API and more. It's easy.

Some providers give us a free service for 14 days with limited storage and bandwidth. But that will be okay for starting point. The only problem is because 'people never try'.

Hope it will help for newbie.


I use uploaded images on my website and I would definitely say option a).

One other thing I'd highly recommend is immediately changing the file name from what the user has named the photo, to something more manageable. For example something with the date and time to uniquely identify each picture.

It also helps to strip the user's file name of any strange characters to avoid future complications.


Definitely resize the image, and check it's format if you can. There have been cases of malicious files being uploaded and served by unwitting hosts- for instance, the GIFAR vulnerability allowed you to hide a malicious java applet in a GIF file, which would then be able to read cookies in the current context and send them to another site for a cross-site scripting attack. Resizing the images usually prevents this, as it munges the embedded code. While this attack has been fixed by JVM patches, naively serving up binary files without scrubbing them opens you up to a whole range of vulnerabilities.

Remember, most virus scanners can only run against the filesystem- if you store your binaries in the DB, you won't be able to run a scanner against them very easily.


This is basically I do.

  1. Store an uploaded image in temporary directory or memory.
  2. Process that image before permanently storing it. 2.1. Color corrections 2.2. Compress 2.3. Create several copies based on image dimensions 2.4. Rename with .xl, .lg, .md, .sm etc. suffixes
  3. Pack all processed image files (from a single file) inside a folder with folder name as id which will be stored in database for any row/document along with image file name (or may be random name as image name).
  4. Create yyyy/mm/d path folder if doesn't exist. For example 2016/08/21. Remember that path and store in database for same document and row.
  5. Move image id folder to path folder. (Path folder may be located in /var/web-content folder.)
  6. Flush memory buffer or delete temporary file.

When you need to access any image mentioned in a document, you have the path and id of the folder than contains images. For example /var/web-content/{{path}}/{{id}}/image-file-name.sm.jpg

This way if you have to delete all processed image files, just delete the folder and it's content recursively.


Most implementations are option A.

With option B, you open a whole big can of whoop4ss when you marshall those bits from the database into something that can be displayed on a browser... Also, if the db is down, the images are not available.

I don't think that space is too much of an issue... Terabyte drives are a couple hundred bucks now.

We are implementing with option A because we don't have the time or resources to do option B.


For auto resizing, try imagemagick... it is used for many major open source content/photo management systems... and I believe that there are some .net extensions for it.


There's sort of a hybrid approach in SQL Server 2008 called the filestream datatype that was talked about on RunAs Radio #74, which is sort of like the best of both worlds. Most people don't have the 2008 otion, but if you do, this option looks pretty cool


We use A. I would put it on a shared drive (unless you don't plan on running more than one server).

If the time comes when this won't scale for you then you can investigate caching mechanisms.


Absolutely, positively option A. Others have mentioned that databases generally don't deal well with BLOBs, whether they're designed to do so or not. Filesystems, on the other hand, live for this stuff. You have the option of using RAID striping, spreading images across multiple drives, even spreading them across geographically disparate servers.

Another advantage is your database backups/replication would be monstrous.


Option A.

Once the image is loaded you can verify the format and resize it before saving. There a number of .Net code samples to resize images on http://www.codeproject.com. For instance: http://www.codeproject.com/KB/cs/Photo_Resize.aspx


For security reasons, it is also best practise to avoid problems caused by IE's Content Sniffing which can allow attackers to upload JavaScript inside image files, which might get executed in the context of your site. So you might want to transform the images (crop/resize them) somehow before storing them to prevent this sort of attack. This answer has some other ideas.


Well, I have a similar project where users upload files onto the server. Under my point of view, option a) is the best solution due to it's more flexible. What you must do is storing images in a protected folder classified by subdirectories. The main directory must be set up by the administrator as the content must no run scripts (very important) and (read, write) protected for not be accesible in http request.

I hope this helps you.


If they are small files that will not need to be edited then option B is not a bad option. I prefer this to writing logic to store files and deal with crazy directory structure issues. Having a lot of files in one directory is bad. emkay?

If the files are large or require constant editing, especially from programs like office, then option A is your best bet.

For most cases, it's a matter of preference, but if you go option A, just make re the directories don't have too many files in them. If you choose option B, then make the table with the BLOBed data be in it's own database and/or file group. This will help with maintenance, especially backups/restores. Your regular data is probably fairly small, while your image data will be huge over time.


It depends on your requirements, specially volume, users and frequency of search. But, for small or medium office, the best option is to use an application like Apple Photos or Adobe Lighroom. They are specialized to store, catalog, index, and organize this kind of resource. But, for large organizations, with strong requirements of storage and high number of users, it is recommend instantiate an Content Management plataform with a Digital Asset Management, like Nuxeo or Alfresco; both offers very good resources do manage very large volumes of data with simplified methods to retrive them. And, very important: there is an free (open source) option for both platforms.

참고URL : https://stackoverflow.com/questions/348363/what-is-the-best-place-for-storing-uploaded-images-sql-database-or-disk-file-sy

반응형