Uploading a ZIP with an input generates an erroneous file

0

I have a

<input name="shp_local" id="shp_local" type="file" ></input>

I can upload files of any kind and the temp file generated on the server is correct, but when I upload .zip it generates a bigger and more inconsistent file.

I'm using tomcat 7.0

When uploading larger files I have no problems, apparently this happens only when sending compressed files. To check the information I receive on the server I am using the .tmp file that is generated automatically.

Edit 1

The input is surrounded by a form that launches a servlet, this is the code for processing the file in the servlet

PrintWriter outwr = response.getWriter();
String fileType = null;
String fileName = "";
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
    List /* FileItem */items = upload.parseRequest(request);
    Iterator iterator = items.iterator();
    while (iterator.hasNext()) {
        FileItem item = (FileItem) iterator.next();
        if (!item.isFormField()) {
            InputStream inputStream = item.getInputStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(inputStream, writer);
            // creem un arxiu temporal
            File temp = File.createTempFile("tempfile", ".tmp");
            Writer out = new BufferedWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(
                                    temp.getAbsolutePath())));
            try {
                out.write(writer.toString());
            } finally {
                out.close();
            }
            fileName = temp.getName();
        } else {
            fileType = item.getString();
        }
    }
    
asked by Oshant 20.11.2017 в 12:13
source

1 answer

1

The problem is here:

StringWriter writer 
out.write(writer.toString());

You are converting a binary file into text, that's why it gets bigger. StringWriter is used to write text. You need to handle the data flow as binary. Use another implementation such as FileOutputStream with a byte buffer and make sure you are typing bytes and not Strings . There are also several frameworks that facilitate the handling of files like the commons-fileupload that is used in Struts2.

Try this way:

byte[] bufer = new byte[8192];
FileOutputStream fos = null;

File temp = File.createTempFile("tempfile", ".tmp");
fos = new FileOutputStream(temp);

int cuenta;
while ((cuenta = fis.read(bufer)) > 0) {
    fos.write(bufer, 0, cuenta);
}
    
answered by 20.11.2017 / 20:41
source