How to save the path of an image in the database?

5

I'm using JDBC and taking an image to save to the database. But I want to save the image to HD and save it to the bank only the path ( path ) of it.

I wanted to know what is the best type I use to manipulate and save the image ( Image or File ). Since most of the functions of File are relative to String ;

The image is selected by the form of the html and passed as if it were a servlet , however, I use it in a Controller so that it is a simpler and more cohesive code.

    
asked by anonymous 18.12.2014 / 13:29

2 answers

2

Saving the full path

To save to a database you must save the path as a String .

Obviously your code that reads and writes the records can encapsulate this String in a File , for example, retrieving the String bank and creating a File or retrieving the file path as String and writing to database.

In this situation, do whatever is most convenient.

Organizing the files

However, unless it is an absolutely necessary requirement of your system, I would not save the full path of the files.

In general, it would be more appropriate to define a directory in the program configuration and save all selected files in that directory.

Then you can save only the names of images in the database, and when you need to save the file, just do something like:

new File(configuracao.getPastaArquivos(), nomeArquivo)

Incidentally, neither is the filename required. If you have, for example, a table in the database where you save the file information, you can simply save the file in the folder using the ID as the name.

So the path on the disk would look something like this:

new File(configuracao.getPastaArquivos(), arquivo.getId())

In this way, the data in the file (such as your name) stays in the database and you have everything organized into a folder by the ID.

Easier to back up, move files to another location if needed, and also avoid problems with special characters in names, spaces, and accents. It also allows situations where two system users send a file with the same name.

    
18.12.2014 / 20:37
3

Can not for security reasons.

Quite simply: No site needs to know anything about the user's filesystem. When a file is sent to a server only its data is important.

In Firefox you can still see the mozFullPath that shows the absolute path of a file using Javascript, but if you try to get / use this value it will return an empty string.

/* CTRL+SHIFT+J para ver a mensagem no console. */

document.getElementById('file').onchange = function(){
    console.dir(this.files[0]);
    console.log("mozFullPath: " + this.files[0]['mozFullPath']); // vai retornar ""
};
<input id='file' type='file'/>

You'll see something like this:

    
19.12.2014 / 08:33