How to save image in database?

Asked

Viewed 773 times

1

I am developing a web application using the play framework, in which I am finishing the CRUD of a user, however this missing only the part where the user saves his profile photos in the register. As I have little experience with the web, I’m having trouble saving the user’s image and then returning it to the listing screen.

This is my class of record:

public class Funcionarios extends Controller {

public static void form() { 
    long funcCount = Agente.count();
    System.out.println(funcCount);
    render(funcCount);
}

@AuditoriaOvitrampas
public static void cadastrar(@Valid Agente funcionario, String senha) throws Exception {

    Agente funcionarioBanco = Agente.find("email = ? or login = ?", funcionario.email, funcionario.login).first();

    if (funcionario.id == null) {
        if (funcionarioBanco != null && funcionarioBanco.id != funcionarioBanco.id && funcionarioBanco.foto == null) {
            validation.addError("funcionario.email", "E-mail já existente");
            validation.addError("funcionario.login", "Usuário já existente");
            validation.addError("funcionario.foto", "Imagem já cadastrada");
        }
        if (validation.hasErrors() || !funcionario.senha.equals(senha)) {
            validation.addError("funcionario.senha", "Senha não corresponde");
            params.flash();
            validation.keep();
            form();
        }
        funcionario.senha = Crypto.passwordHash(senha);
        validation.valid("cadastrado com sucesso");
        funcionario.save();
        session.get("usuarioLogado");
        listar(null);
    } else {
        validation.valid("editado com sucesso");
        funcionario.save();
        session.get("usuarioLogado");
        listar(null);

    }
}

public static void detalhesFuncionarios(Long id) {
    Agente f = Agente.findById(id);
    renderTemplate("Funcionarios/detalhesFuncionarios.html", f);
}
@AuditoriaOvitrampas
public static void editarFuncionarios(Long id) {
    Agente f = Agente.findById(id);
    renderTemplate("Funcionarios/form.html", f);
}

public static void listar(String parametroBusca) {
    List<Agente> funcionarios = null;
    if (parametroBusca == null) {
        funcionarios = Agente.find("status != ?", Status.INATIVO).fetch();          
    }
    render(funcionarios, parametroBusca);
}
@AuditoriaOvitrampas
public static void perfil(Long id){
    String perfil = session.get("usuarioLogado");
    Agente f = Agente.find("login = ?", perfil).first();
    renderTemplate("Funcionarios/perfil.html", f);
}
@AuditoriaOvitrampas
public static void removerFuncionarios(Long id) {
    Agente funcionario = Agente.findById(id);

    if(funcionario.email.equals("[email protected]")){
        validation.addError("funcionario.email", "E-mail já existente");
        listar(null);
    }
    funcionario.status = Status.INATIVO;
    funcionario.save();
    flash.success("Removido com sucesso");
    listar(null);
}

public static void formTrocarSenha() {
    render();
}

public static void trocarSenha(String senhaAtual, String novaSenha1, String novaSenha2){
    String senha = session.get("usuarioSenha");
    if(senha.equals(Crypto.passwordHash(senhaAtual))){
        if(novaSenha1.equals(novaSenha2)) {
            Agente f = Agente.findById(Long.parseLong(session.get("usuarioId")));
            f.senha = Crypto.passwordHash(novaSenha1);
            f.save();
            session.put("usuarioSenha", f.senha);
            renderTemplate("Funcionarios/perfil.html", f);
            flash.success("Senha alterada com sucesso!");
        }
        else{
            flash.error("Senhas não são iguais");
            renderTemplate("Funcionarios/formTrocarSenha.html");

        }
    } else {
        flash.error("Senha atual não corresponde a senha do usuário");
        renderTemplate("Funcionarios/formTrocarSenha.html");

    }
}
}

My model:

@Entity
public class Agente extends Model{
@Required
public String nome;
@Required
public String funcao;
@Required
@MinSize(6)
public String login;
@MinSize(6)
@MaxSize(15)
public String senha;
@Required
@Email
public String email;
public Blob foto;

@OneToMany(mappedBy="agente")
public List<Palheta> palhetas;

@Enumerated(EnumType.STRING)
public Status status;

public Agente() {
    status = Status.ATIVO;
}

And my HTML form:

<section class="forms">
<form action="@{funcionarios.cadastrar}" method="post">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-6">
                <input type="hidden" name="funcionario.id" value="${f?.id}" />
                <div class="form-group">
                    <label>Nome completo:</label> <input type="text"
                        name="funcionario.nome" class="form-control"
                        value="${flash['funcionario.nome'] ? flash['funcionario.nome'] : f?.nome}">
                    <span class="alert-danger">#{error 'funcionario.nome' /}</span>
                </div>

                <div class="form-group">
                    <label>Email:</label> <input type="email" name="funcionario.email"
                        class="form-control" placeholder="[email protected]"
                        value="${flash['funcionario.email'] ? flash['funcionario.email'] : f?.email}">
                    <span class="alert-danger">#{error 'funcionario.email' /}</span>
                </div>

                <div class="form-group">
                    <label>Função:</label> <select name="funcionario.funcao"
                        class="form-control"
                        value="${flash['funcionario.funcao'] ? flash['funcionario.funcao'] : f?.funcao}">
                        <option>Agente de Endemias</option>
                        <option>Laboratorista</option>
                    </select> <span class="alert-danger">#{error 'funcionario.funcao' /}</span>
                </div>
                <div class="form-group">
                    <label>Adicionar foto do perfil:</label> <input type="file"
                        name="funcionario.foto" class="form-control">
                </div>
            </div>

            <div class="col-lg-6">
                #{if f}
                <div class="form-group">
                    <label>Matrícula:</label> <input id="loginUsuario" type="text"
                        placeholder="Mínimo 5 caracteres" name="funcionario.login"
                        class="form-control" disabled="disabled"
                        value="${flash['funcionario.login'] ? flash['funcionario.login'] : f?.login}">
                    <span class="alert-danger">#{error 'funcionario.login' /}</span>
                </div>
                #{/if} #{ifnot f}
                <div class="form-group">
                    <label>Matrícula:</label> <input id="loginUsuario" type="text"
                        placeholder="Mínimo 5 caracteres" name="funcionario.login"
                        class="form-control"
                        value="${flash['funcionario.login'] ? flash['funcionario.login'] : f?.login}">
                    <span class="alert-danger">#{error 'funcionario.login' /}</span>
                </div>
                <div class="form-group">
                    <label>Senha:</label> <input type="password"
                        name="funcionario.senha" class="form-control"
                        placeholder="Mínimo 6 caracteres"
                        value="${flash['funcionario.senha'] ? flash['funcionario.senha'] : f?.senha}">
                    <span class="alert-danger">#{error 'funcionario.senha' /}</span>
                </div>
                <div class="form-group">
                    <label>Confirmar senha:</label> <input type="password"
                        placeholder="Mínimo 6 caracteres" name="senha"
                        class="form-control"> <span class="alert-danger">#{error
                        'senha' /}</span>
                </div>
            </div>
            #{/ifnot}
            <div class="col-lg-12">
                <button type="submit" class="btn btn-primary">Salvar</button>
                <button type="reset" class="btn btn-danger"
                    onclick="window.location.href='/funcionarios/listar';">
                    Cancelar</button>
            </div>
        </div>
    </div>
</form>

inserir a descrição da imagem aqui

  • 1

    I’m not familiar with the framework, but look for LOB or BLOB data types in your database,

  • Can you do it in java? I think if you give me a hint in java I can unwind the rest, eh q have no idea how to start.

  • I need to know if the database is a basic MYSQL type or the framework has its own database type?

  • For now I’m using the very bank of play the H2, which is a local bank.

  • An example in PHP, I used a command to "serialize" any object/image/array in "string", then save it in the database as "LOB" format (for large texts), then when retrieving I just "deserialize" the string into an object. I know that in java has the interface "Serializable" for this, but I only worked with local file

  • https://stackoverflow.com/questions/28145713/does-h2-support-the-serializable-isolation-level

Show 1 more comment

1 answer

0


You can create a Mouse database for the images and save the image using the Mouse Docker. It’s quite simple. And in your main bank you save the id that references the image in Mongo.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.