I am building a Social Network project with Angular, Spring and MySQL. I am trying to build a system in the backend that takes images and then stores it into the database.
public class Image {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long imageId;
private String path;
@Lob
private byte[] data;
}
The idea was taking the image the user sent as a MultipartFile, convert it into bytes and then store it into the Image.data value.
I didn't try it yet, because I had some doubts: is it the most efficient way of storing a file into the database? And most importantly, can't a user just upload some sort of malicious file into the database? If yes, can I prevent that?
CodePudding user response:
You can assert the buffer from certain types of file headers, for instance the .png
format has a different header than a .dmg
or .exe
have. The logical thing to do would be to ensure that the header matches the protocol, and if it doesn't, don't insert into the database.
As for storage, it really depends on the your hardware, however if you are going the route of inserting raw parts, I recommend compressing it before inserting into the database.
CodePudding user response:
I don't know about the most efficient method to do this, but yes: an attacker could upload a malicious file. Checking that the file is a valid png/jpg/... is a first step. In any case if you only use prepared statements and never try to execute some image you should be OK
CodePudding user response:
Apache Tika: Allows you to easily determine the content type by file headers.
But since you stated that you're actually building some kind of Social Network, you probably need to parse the metadata (EXIF) and/or resize the image anyway. Any library to do so should throw an Exception when the file passed to it isn't a valid image file, therefore already solving your problems.