Save a file in the database without creating a virtual directory

0

good morning,

I'm having a problem, I'm doing a project in Java and I upload it to the app engine, but app engine has a problem and it does not allow creating virtual directories, so what I want to do to solve this problem, is to save my files in DataStore and be able to download them without needing them to be in a virtual directory, the code that I have is the following:

protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
         if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.println("Error: El formulario debe contener enctype=multipart/form-data");
            writer.flush();
            return;
         }
         DiskFileItemFactory factory = new DiskFileItemFactory();
         factory.setSizeThreshold(MEMORY_THRESHOLD);
         factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
         ServletFileUpload upload = new ServletFileUpload(factory);
         upload.setFileSizeMax(MAX_FILE_SIZE);
         upload.setSizeMax(MAX_REQUEST_SIZE);
         String uploadPath = getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
         File uploadDir = new File(uploadPath);
         if (!uploadDir.exists()) {
             uploadDir.mkdir();
         }
         try {
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {

            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    HttpSession session = request.getSession();
                    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    System.out.println(filePath);
                    item.write(storeFile);
                    Cuenta cuenta=new Cuenta();

                    //Covertir archivo en Base64
                    Base64 base64 = new Base64();
                    File file = new File(filePath);
                    byte[] fileArray = new byte[(int) file.length()];
                    InputStream inputStream;
                    Text encodedFile = new Text("");
                    try {
        inputStream = new FileInputStream(file);
        inputStream.read(fileArray);
        encodedFile =new Text(base64.encodeToString(fileArray));
                    cuenta.setCertificado(encodedFile);
                    cuenta.setId(Long.parseLong(session.getAttribute("cuenta").toString()));
                    } catch (Exception e) {
                           request.setAttribute("message","Ocurrio un error codificando el archivo.");
                           RequestDispatcher rd=request.getRequestDispatcher("Cuentas");
                           rd.forward(request, response);
                    }

                    Result respuesta=cuenta.Salvar(datastore, "");
                    request.setAttribute("message","Archivo cargado con exito");
                    RequestDispatcher rd=request.getRequestDispatcher("Cuentas");
                    rd.forward(request, response);
                }
            }
        }
    } catch (Exception ex) {
           request.setAttribute("message","Ocurrio un error cargando el archivo");
           RequestDispatcher rd=request.getRequestDispatcher("Cuentas");
           rd.forward(request, response);
    }
}

What do I do? In my form I upload the file, and I come to the servlet and I take the file, I keep it in a virtual directory and I agree to base64, but as I can receive the file, and from a pass to base 64 without creating the virtual directory, it can be ? I remain attentive to any questions, thank you.

    
asked by afar1793 16.02.2018 в 14:21
source

2 answers

0

You can use this example to create your String64 not creating the virtuous path, it has the same parameters, I hope it works for you

import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Base64Servlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String imageBase64 = req.getParameter("base64");
    OutputStream out = resp.getOutputStream();
    writeOutputStream(imageBase64, out);

    resp.setContentType("image/png");
    resp.setHeader("Pragma", "");
    resp.setHeader("Cache-Control", "");
    resp.setHeader("Content-Disposition", "inline; fileName=image.png");
}

private void writeOutputStream(String value, OutputStream outputStream) throws IOException {
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] imgBytes = decoder.decodeBuffer(value);
    BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(imgBytes));
    ImageIO.write(bufImg, "png", outputStream);
}
}
    
answered by 16.02.2018 в 22:15
0

For your situation, the ideal would be to use cloud storage , which is a distributed file service designed to work with Google Cloud products.

    
answered by 23.07.2018 в 20:43