Example usage for org.apache.commons.fileupload FileItem write

List of usage examples for org.apache.commons.fileupload FileItem write

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem write.

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:isl.FIMS.servlet.imports.ImportXML.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    this.initVars(request);
    String username = getUsername(request);

    Config conf = new Config("EisagwghXML_RDF");
    String xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl";
    String displayMsg = "";
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    StringBuilder xml = new StringBuilder(
            this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
    //  ArrayList<String> notValidMXL = new ArrayList<String>();
    HashMap<String, ArrayList> notValidMXL = new <String, ArrayList>HashMap();
    if (!ServletFileUpload.isMultipartContent(request)) {
        displayMsg = "form";
    } else {// w  ww  .  jav  a 2s.  c o  m
        // configures some settings
        String filePath = this.export_import_Folder;
        java.util.Date date = new java.util.Date();
        Timestamp t = new Timestamp(date.getTime());
        String currentDir = filePath + t.toString().replaceAll(":", "");
        File saveDir = new File(currentDir);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        factory.setRepository(saveDir);
        ArrayList<String> savedIDs = new ArrayList<String>();

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(REQUEST_SIZE);
        // constructs the directory path to store upload file
        String uploadPath = currentDir;
        int xmlCount = 0;
        String[] id = null;
        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterates over form's fields
            File storeFile = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = uploadPath + File.separator + fileName;
                    storeFile = new File(filePath);
                    item.write(storeFile);
                    Utils.unzip(fileName, uploadPath);
                    File dir = new File(uploadPath);

                    String[] extensions = new String[] { "xml", "x3ml" };
                    List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
                    xmlCount = files.size();
                    for (File file : files) {
                        // saves the file on disk
                        Document doc = ParseXMLFile.parseFile(file.getPath());
                        String xmlContent = doc.getDocumentElement().getTextContent();
                        String uri_name = "";
                        try {
                            uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
                        } catch (DMSException ex) {
                            ex.printStackTrace();
                        }
                        String uriValue = this.URI_Reference_Path + uri_name + "/";
                        boolean insertEntity = false;
                        if (xmlContent.contains(uriValue) || file.getName().contains(type)) {
                            insertEntity = true;
                        }
                        Element root = doc.getDocumentElement();
                        Node admin = Utils.removeNode(root, "admin", true);

                        //  File rename = new File(uploadPath + File.separator + id[0] + ".xml");
                        //  boolean isRename = storeFile.renameTo(rename);
                        //   ParseXMLFile.saveXMLDocument(rename.getPath(), doc);
                        String schemaFilename = "";
                        schemaFilename = type;

                        SchemaFile sch = new SchemaFile(schemaFolder + schemaFilename + ".xsd");
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer transformer = tf.newTransformer();
                        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        StringWriter writer = new StringWriter();
                        transformer.transform(new DOMSource(doc), new StreamResult(writer));
                        String xmlString = writer.getBuffer().toString().replaceAll("\r", "");

                        //without admin
                        boolean isValid = sch.validate(xmlString);
                        if ((!isValid && insertEntity)) {
                            notValidMXL.put(file.getName(), null);
                        } else if (insertEntity) {
                            id = initInsertFile(type, false);
                            doc = createAdminPart(id[0], type, doc, username);
                            writer = new StringWriter();
                            transformer.transform(new DOMSource(doc), new StreamResult(writer));
                            xmlString = writer.getBuffer().toString().replaceAll("\r", "");
                            DBCollection col = new DBCollection(this.DBURI, id[1], this.DBuser,
                                    this.DBpassword);
                            DBFile dbF = col.createFile(id[0] + ".xml", "XMLDBFile");
                            dbF.setXMLAsString(xmlString);
                            dbF.store();
                            ArrayList<String> externalFiles = new <String>ArrayList();
                            ArrayList<String> externalDBFiles = new <String>ArrayList();

                            String q = "//*[";
                            for (String attrSet : this.uploadAttributes) {
                                String[] temp = attrSet.split("#");
                                String func = temp[0];
                                String attr = temp[1];
                                if (func.contains("text")) {
                                    q += "@" + attr + "]/text()";
                                } else {
                                    q = "data(//*[@" + attr + "]/@" + attr + ")";
                                }
                                String[] res = dbF.queryString(q);
                                for (String extFile : res) {
                                    externalFiles.add(extFile + "#" + attr);
                                }
                            }
                            q = "//";
                            if (!dbSchemaPath[0].equals("")) {
                                for (String attrSet : this.dbSchemaPath) {
                                    String[] temp = attrSet.split("#");
                                    String func = temp[0];
                                    String path = temp[1];
                                    if (func.contains("text")) {
                                        q += path + "//text()";
                                    } else {
                                        q = "data(//" + path + ")";
                                    }
                                    String[] res = dbF.queryString(q);
                                    for (String extFile : res) {
                                        externalDBFiles.add(extFile);
                                    }
                                }
                            }
                            ArrayList<String> missingExternalFiles = new <String>ArrayList();
                            for (String extFile : externalFiles) {
                                extFile = extFile.substring(0, extFile.lastIndexOf("#"));

                                List<File> f = (List<File>) FileUtils.listFiles(dir,
                                        FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE);
                                if (f.size() == 0) {
                                    missingExternalFiles.add(extFile);
                                }
                            }
                            if (missingExternalFiles.size() > 0) {
                                notValidMXL.put(file.getName(), missingExternalFiles);
                            }

                            XMLEntity xmlNew = new XMLEntity(this.DBURI, this.systemDbCollection + type,
                                    this.DBuser, this.DBpassword, type, id[0]);

                            ArrayList<String> worngFiles = Utils.checkReference(xmlNew, this.DBURI, id[0], type,
                                    this.DBuser, this.DBpassword);
                            if (worngFiles.size() > 0) {
                                //dbF.remove();
                                notValidMXL.put(file.getName(), worngFiles);
                            }
                            //remove duplicates from externalFiles if any
                            HashSet hs = new HashSet();
                            hs.addAll(missingExternalFiles);
                            missingExternalFiles.clear();
                            missingExternalFiles.addAll(hs);
                            if (missingExternalFiles.isEmpty() && worngFiles.isEmpty()) {

                                for (String extFile : externalFiles) {
                                    String attr = extFile.substring(extFile.lastIndexOf("#") + 1,
                                            extFile.length());
                                    extFile = extFile.substring(0, extFile.lastIndexOf("#"));

                                    List<File> f = (List<File>) FileUtils.listFiles(dir,
                                            FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE);
                                    File uploadFile = f.iterator().next();
                                    String content = FileUtils.readFileToString(uploadFile);

                                    DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection,
                                            "Uploads.xml", this.DBuser, this.DBpassword);
                                    String mime = Utils.findMime(uploadsDBFile, uploadFile.getName(), attr);
                                    String uniqueName = Utils.createUniqueFilename(uploadFile.getName());
                                    File uploadFileUnique = new File(uploadFile.getPath().substring(0,
                                            uploadFile.getPath().lastIndexOf(File.separator)) + File.separator
                                            + uniqueName);
                                    uploadFile.renameTo(uploadFileUnique);
                                    xmlString = xmlString.replaceAll(uploadFile.getName(), uniqueName);
                                    String upload_path = this.systemUploads + type;
                                    File upload_dir = null;
                                    ;
                                    if (mime.equals("Photos")) {
                                        upload_path += File.separator + mime + File.separator + "original"
                                                + File.separator;
                                        upload_dir = new File(upload_path + uniqueName);
                                        FileUtils.copyFile(uploadFileUnique, upload_dir);
                                        Utils.resizeImage(uniqueName, upload_path,
                                                upload_path.replaceAll("original", "thumbs"), thumbSize);
                                        Utils.resizeImage(uniqueName, upload_path,
                                                upload_path.replaceAll("original", "normal"), normalSize);
                                        xmlString = xmlString.replace("</versions>",
                                                "</versions>" + "\n" + "<type>Photos</type>");
                                    } else {
                                        upload_path += File.separator + mime + File.separator;
                                        upload_dir = new File(upload_path + uniqueName);
                                        FileUtils.copyFile(uploadFileUnique, upload_dir);
                                    }
                                    if (!dbSchemaFolder.equals("")) {
                                        if (externalDBFiles.contains(extFile)) {
                                            try {
                                                DBCollection colSchema = new DBCollection(this.DBURI,
                                                        dbSchemaFolder, this.DBuser, this.DBpassword);
                                                DBFile dbFSchema = colSchema.createFile(uniqueName,
                                                        "XMLDBFile");
                                                dbFSchema.setXMLAsString(content);
                                                dbFSchema.store();
                                            } catch (Exception e) {
                                            }
                                        }
                                    }
                                    uploadFileUnique.renameTo(uploadFile);

                                }
                                dbF.setXMLAsString(xmlString);
                                dbF.store();
                                Utils.updateReferences(xmlNew, this.DBURI, id[0].split(type)[1], type,
                                        this.DBpassword, this.DBuser);
                                Utils.updateVocabularies(xmlNew, this.DBURI, id[0].split(type)[1], type,
                                        this.DBpassword, this.DBuser, lang);
                                savedIDs.add(id[0]);
                            } else {
                                dbF.remove();
                            }

                        }
                    }

                }
            }
            Document doc = ParseXMLFile.parseFile(ApplicationConfig.SYSTEM_ROOT + "formating/multi_lang.xml");
            Element root = doc.getDocumentElement();
            Element contextTag = (Element) root.getElementsByTagName("context").item(0);
            String uri_name = "";
            try {
                uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
            } catch (DMSException ex) {
            }
            if (notValidMXL.size() == 0) {
                xsl = conf.DISPLAY_XSL;
                displayMsg = Messages.ACTION_SUCCESS;
                displayMsg += Messages.NL + Messages.NL + Messages.URI_ID;
                String uriValue = "";
                xml.append("<Display>").append(displayMsg).append("</Display>\n");
                xml.append("<backPages>").append('2').append("</backPages>\n");

                for (String saveId : savedIDs) {
                    uriValue = this.URI_Reference_Path + uri_name + "/" + saveId + Messages.NL;
                    xml.append("<codeValue>").append(uriValue).append("</codeValue>\n");

                }

            } else if (notValidMXL.size() >= 1) {
                xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl";

                Iterator it = notValidMXL.keySet().iterator();
                while (it.hasNext()) {

                    String key = (String) it.next();
                    ArrayList<String> value = notValidMXL.get(key);

                    if (value != null) {
                        displayMsg += "<line>";
                        Element select = (Element) contextTag.getElementsByTagName("missingReferences").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                        displayMsg = displayMsg.replace("?", key);
                        for (String mis_res : value) {

                            displayMsg += mis_res + ",";
                        }
                        displayMsg = displayMsg.substring(0, displayMsg.length() - 1);
                        displayMsg += ".";
                        displayMsg += "</line>";

                    } else {
                        displayMsg += "<line>";
                        Element select = (Element) contextTag.getElementsByTagName("NOT_VALID_XML").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                        displayMsg = displayMsg.replace(";", key);
                        displayMsg += "</line>";
                    }
                    displayMsg += "<line>";
                    displayMsg += "</line>";
                }
                if (notValidMXL.size() < xmlCount) {
                    displayMsg += "<line>";
                    Element select = (Element) contextTag.getElementsByTagName("rest_valid").item(0);
                    displayMsg += select.getElementsByTagName(lang).item(0).getTextContent();
                    displayMsg += "</line>";
                    for (String saveId : savedIDs) {
                        displayMsg += "<line>";
                        String uriValue = this.URI_Reference_Path + uri_name + "/" + saveId;
                        select = (Element) contextTag.getElementsByTagName("URI_ID").item(0);
                        displayMsg += select.getElementsByTagName(lang).item(0).getTextContent() + ": "
                                + uriValue;
                        displayMsg += "</line>";
                    }
                }
            }
            Utils.deleteDir(currentDir);
        } catch (Exception ex) {
            ex.printStackTrace();
            displayMsg += Messages.NOT_VALID_IMPORT;
        }

    }
    xml.append("<Display>").append(displayMsg).append("</Display>\n");
    xml.append("<EntityType>").append(type).append("</EntityType>\n");
    xml.append(this.xmlEnd());
    try {
        XMLTransform xmlTrans = new XMLTransform(xml.toString());
        xmlTrans.transform(out, xsl);
    } catch (DMSException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:com.krawler.spring.importFunctionality.ImportController.java

public ModelAndView fileUploadXLSX(HttpServletRequest request, HttpServletResponse response) {
    String View = "jsonView-ex";
    JSONObject jobj = new JSONObject();
    try {//  w w w. java 2 s.c om
        System.out.println("A(( Upload XLSX start : " + new Date());
        jobj.put("success", true);
        FileItemFactory factory = new DiskFileItemFactory(4096,
                new File(ConfigReader.getinstance().get("UploadTempDir", "/tmp")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(10485760); // 10Mb
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "xlsfiles";
        String fileName = null;
        String fileid = UUID.randomUUID().toString();
        fileid = fileid.replaceAll("-", ""); // To append UUID without "-" [SK]
        String Ext = "";
        while (i.hasNext()) {
            java.io.File destDir = new java.io.File(destinationDirectory);
            if (!destDir.exists()) { //Create xls file's folder if not present
                destDir.mkdirs();
            }

            FileItem fi = (FileItem) i.next();
            if (fi.isFormField())
                continue;
            fileName = fi.getName();
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
                int startIndex = fileName.contains("\\") ? (fileName.lastIndexOf("\\") + 1) : 0;
                fileName = fileName.substring(startIndex, fileName.lastIndexOf("."));
            }

            if (fileName.length() > 28) { // To fixed Mysql ERROR 1103 (42000): Incorrect table name
                throw new DataInvalidateException("Filename is too long, use upto 28 characters.");
            }
            fi.write(new File(destinationDirectory, fileName + "_" + fileid + Ext));
        }

        FileInputStream fs = new FileInputStream(destinationDirectory + "/" + fileName + "_" + fileid + Ext);
        XSSFWorkbook wb = new XSSFWorkbook(fs);
        int count = wb.getNumberOfSheets();
        JSONArray jArr = new JSONArray();
        for (int x = 0; x < count; x++) {
            JSONObject obj = new JSONObject();
            obj.put("name", wb.getSheetName(x));
            obj.put("index", x);
            jArr.put(obj);
        }
        jobj.put("file", destinationDirectory + "/" + fileName + "_" + fileid + Ext);
        jobj.put("filename", fileName + "_" + fileid + Ext);
        jobj.put("data", jArr);
        jobj.put("msg", "Image has been successfully uploaded");
        jobj.put("lsuccess", true);
        jobj.put("valid", true);
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        Logger.getLogger(ImportController.class.getName()).log(Level.SEVERE, null, ex);
        jobj.put("msg", "File exceeds max size limit i.e 10MB.");
        jobj.put("lsuccess", false);
        jobj.put("valid", true);
    } catch (Exception e) {
        Logger.getLogger(ImportController.class.getName()).log(Level.SEVERE, null, e);
        try {
            jobj.put("msg", e.getMessage());
            jobj.put("lsuccess", false);
            jobj.put("valid", true);
        } catch (Exception ex) {
        }
    } finally {
        System.out.println("A(( Upload XLS end : " + new Date());
        return new ModelAndView(View, "model", jobj.toString());
    }
}

From source file:hoot.services.controllers.ingest.FileUploadResourceTest.java

@Ignore
@Test/*  w  w w .j  av  a  2s  .co m*/
@Category(UnitTest.class)
public void TestserializeFGDB() throws Exception {
    FileUploadResource res = new FileUploadResource();

    //homeFolder + "/upload/" + jobId + "/" + relPath;
    // Create dummy FGDB

    String jobId = "123-456-789";
    String wkdirpath = homeFolder + "/upload/" + jobId;
    File workingDir = new File(wkdirpath);
    FileUtils.forceMkdir(workingDir);
    org.junit.Assert.assertTrue(workingDir.exists());

    List<FileItem> fileItemsList = new ArrayList<FileItem>();

    FileItemFactory factory = new DiskFileItemFactory(16, null);
    String textFieldName = "textField";

    FileItem item = factory.createItem(textFieldName, "application/octet-stream", true,
            "fgdbTest.gdb/dummy1.gdbtable");

    String textFieldValue = "0123456789";
    byte[] testFieldValueBytes = textFieldValue.getBytes();

    OutputStream os = item.getOutputStream();
    os.write(testFieldValueBytes);
    os.close();

    File out = new File(wkdirpath + "/buffer.tmp");
    item.write(out);
    fileItemsList.add(item);
    org.junit.Assert.assertTrue(out.exists());

    /*
        Map<String,String> uploadedFiles = new HashMap<String, String>();
        Map<String,String> uploadedFilesPaths = new HashMap<String, String>();
            
          res._serializeFGDB(fileItemsList, jobId,
    uploadedFiles, uploadedFilesPaths );
            
          org.junit.Assert.assertEquals("GDB", uploadedFiles.get("fgdbTest"));
          org.junit.Assert.assertEquals("fgdbTest.gdb", uploadedFilesPaths.get("fgdbTest"));
            
          File fgdbpath = new File(wkdirpath + "/fgdbTest.gdb");
          org.junit.Assert.assertTrue(fgdbpath.exists());
            
          File content = new File(wkdirpath + "/fgdbTest.gdb/dummy1.gdbtable");
          org.junit.Assert.assertTrue(content.exists());
            
          FileUtils.forceDelete(workingDir);*/
}

From source file:com.krawler.spring.importFunctionality.ImportController.java

public ModelAndView fileUploadXLS(HttpServletRequest request, HttpServletResponse response) {
    String View = "jsonView-ex";
    JSONObject jobj = new JSONObject();
    try {/*from  w w w.  ja  va 2  s . c  o  m*/
        System.out.println("A(( Upload XLS start : " + new Date());
        jobj.put("success", true);
        FileItemFactory factory = new DiskFileItemFactory(4096,
                new File(ConfigReader.getinstance().get("UploadTempDir", "/tmp")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(10485760);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "xlsfiles";
        String fileName = null;
        String fileid = UUID.randomUUID().toString();
        fileid = fileid.replaceAll("-", ""); // To append UUID without "-" [SK]
        String Ext = "";
        while (i.hasNext()) {
            java.io.File destDir = new java.io.File(destinationDirectory);
            if (!destDir.exists()) { //Create xls file's folder if not present
                destDir.mkdirs();
            }

            FileItem fi = (FileItem) i.next();
            if (fi.isFormField())
                continue;
            fileName = fi.getName();
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
                int startIndex = fileName.contains("\\") ? (fileName.lastIndexOf("\\") + 1) : 0;
                fileName = fileName.substring(startIndex, fileName.lastIndexOf("."));
            }

            if (fileName.length() > 28) { // To fixed Mysql ERROR 1103 (42000): Incorrect table name
                throw new DataInvalidateException("Filename is too long, use upto 28 characters.");
            }
            fi.write(new File(destinationDirectory, fileName + "_" + fileid + Ext));
        }

        POIFSFileSystem fs = new POIFSFileSystem(
                new FileInputStream(destinationDirectory + "/" + fileName + "_" + fileid + Ext));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        int count = wb.getNumberOfSheets();
        JSONArray jArr = new JSONArray();
        for (int x = 0; x < count; x++) {
            JSONObject obj = new JSONObject();
            obj.put("name", wb.getSheetName(x));
            obj.put("index", x);
            jArr.put(obj);
        }
        jobj.put("file", destinationDirectory + "/" + fileName + "_" + fileid + Ext);
        jobj.put("filename", fileName + "_" + fileid + Ext);
        jobj.put("data", jArr);
        jobj.put("msg", "Image has been successfully uploaded");
        jobj.put("lsuccess", true);
        jobj.put("valid", true);
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        Logger.getLogger(ImportController.class.getName()).log(Level.SEVERE, null, ex);
        jobj.put("msg", "File exceeds max size limit i.e 10MB.");
        jobj.put("lsuccess", false);
        jobj.put("valid", true);
    } catch (Exception e) {
        Logger.getLogger(ImportController.class.getName()).log(Level.SEVERE, null, e);
        try {
            String msg = e.getMessage().contains("Invalid header signature;")
                    ? "Not a real xls file. File contents are not XLS content/corrupted content."
                    : e.getMessage();
            jobj.put("msg", msg);
            jobj.put("lsuccess", false);
            jobj.put("valid", true);
        } catch (Exception ex) {
        }
    } finally {
        System.out.println("A(( Upload XLS end : " + new Date());
        return new ModelAndView(View, "model", jobj.toString());
    }
}

From source file:com.intranet.intr.EmpController.java

@RequestMapping(value = "fotoEmpleado.htm", method = RequestMethod.POST)
public String fotoEmpleado_post(@ModelAttribute("empleado") empleados empleado, BindingResult result,
        HttpServletRequest request, Principal principal) {
    String mensaje = "";
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosPerfil";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);//from  w w w .j  a v  a2 s.  c om

    ServletFileUpload upload = new ServletFileUpload(factory);
    String name = principal.getName();
    empleados po = new empleados();

    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getName());
            File file = new File(ubicacionArchivo, item.getName());
            item.write(file);
            users u = usuarioService.getByLogin(name);
            po = empleadoService.ByNif(u.getNif());
            po.setNombrefotografia(item.getName());
            empleadoService.UpdateImagen(po);
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    //return "redirect:uploadFile.htm";

    return "redirect:ActualizarfotoEmpleado.htm";

}

From source file:com.rapidsist.portal.cliente.editor.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from  w w w  .  ja v a  2s  .  c o m*/
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println("PASO POR EL METODO doPost DEL SERVLET SimpleUploaderServlet");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String typeStr = request.getParameter("Type");

    String currentPath = baseDir + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);
    currentPath = request.getContextPath() + currentPath;

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            fileUrl = currentPath + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    fileUrl = currentPath + "/" + newName;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } else {
                retVal = "202";
                errorMessage = "";
            }
        } catch (Exception ex) {
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();
}

From source file:com.fujitsu.gwt.bewebapp.server.GWTUploadServlet.java

/**
 * Override executeAction to save the received files in a custom place and
 * delete this items from session.// ww  w  . java 2 s . c om
 */
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {

    String response = "";
    int cont = 0;

    String displayName = "";
    String originalName = "";
    String fileExtension = "bin";
    String comments = "";
    String pageId = "";
    String atype = "";
    String newversion = "";
    String existingaid = "";
    String visibility = "";
    File tempFile = null;
    for (FileItem item : sessionFiles) {

        if (false == item.isFormField()) {
            cont++;
            try {

                String fName = item.getName();
                fName = fName.replace('\\', '/');
                int indx = fName.lastIndexOf("/");
                if (indx > 0) {
                    originalName = fName.substring(indx + 1);
                } else {
                    originalName = fName;
                }

                int dotPos = originalName.lastIndexOf(".");
                if (dotPos > 0) {
                    fileExtension = originalName.substring(dotPos + 1);
                }

                String tmpFileName = "upload-" + rd.nextInt();
                // Create a temporary file placed in the default system temp
                // folder
                tempFile = File.createTempFile(tmpFileName, ".bin");
                item.write(tempFile);

                // / Save a list with the received files
                receivedFiles.put(item.getFieldName(), tempFile);
                receivedContentTypes.put(item.getFieldName(), item.getContentType());

                // / Send a customized message to the client.
                response += "Successfully attached the file " + item.getName();

            } catch (Exception e) {
                throw new UploadActionException(e.getMessage());
            }
        } else {
            if ("aname".equals(item.getFieldName())) {
                displayName = item.getString();
            } else if ("desc".equals(item.getFieldName())) {
                comments = item.getString();
            } else if ("pageid".equals(item.getFieldName())) {
                pageId = item.getString();
            } else if ("atype".equals(item.getFieldName())) {
                atype = item.getString();
            } else if ("newversion".equals(item.getFieldName())) {
                newversion = item.getString();
            } else if ("existingaid".equals(item.getFieldName())) {
                existingaid = item.getString();
            } else if ("visibility".equals(item.getFieldName())) {
                visibility = item.getString();
            } else {
                System.out.println("Unknows FiledName:" + item.getFieldName() + "=" + item.getString());
            }
        }

        if (displayName.length() == 0) {
            displayName = originalName;
        } else if (!displayName.endsWith("." + fileExtension)) {
            displayName = displayName + "." + fileExtension;
        }
    }
    try {

        String userKey = (String) request.getSession().getAttribute("userKey");
        UserProfile user = null;
        if (userKey != null) {
            user = UserManager.getUserProfileByKey(userKey);

        } else {
            throw new NGException("nugen.exception.user.must.be.login", null);
        }
        AuthDummy ar = new AuthDummy(user, new StringWriter());
        ar.req = request;
        NGPage ngp = (NGPage) NGPageIndex.getContainerByKeyOrFail(pageId);
        AttachmentRecord attachment = null;

        if (existingaid != null) {
            if ((!existingaid.equals("0") && (existingaid.length() > 0))) {
                attachment = ngp.findAttachmentByIDOrFail(existingaid);
            }
        }

        if (attachment == null) {
            //see if there exists an attachment with that name, and use that
            attachment = ngp.findAttachmentByName(displayName);
        }
        if (attachment == null) {
            //last resort, actually create one
            attachment = ngp.createAttachment();
            attachment.setType("FILE");
        }

        attachment.setDisplayName(displayName);
        attachment.setComment(comments);
        attachment.setModifiedBy(ar.getBestUserId());
        attachment.setModifiedDate(ar.nowTime);
        if (atype.equals("Public")) {
            attachment.setVisibility(1);
        } else {
            attachment.setVisibility(2);
        }

        FileInputStream contentStream = new FileInputStream(tempFile);
        AttachmentVersion av = attachment.streamNewVersion(ar, ngp, contentStream);

        HistoryRecord.createHistoryRecord(ngp, attachment.getId(), HistoryRecord.CONTEXT_TYPE_DOCUMENT,
                ar.nowTime, HistoryRecord.EVENT_DOC_ADDED, ar, "");

        ngp.saveContent(ar, "Modified attachments");
    } catch (Exception e) {
        e.printStackTrace();
        throw new UploadActionException(e.getMessage());
    } finally {
        NGPageIndex.clearLocksHeldByThisThread();
    }

    // / Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    // / Send your customized message to the client.
    return response;
}

From source file:com.fredck.FCKeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 * /*w  w w.  j a va2 s  . co  m*/
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (debug) {
        System.out.println("--- BEGIN DOPOST ---");
    }
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();
    String typeStr = request.getParameter("Type");
    String currentPath = baseDir + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);
    currentPath = request.getContextPath() + currentPath;
    if (debug) {
        System.out.println(currentDirPath);
    }
    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";
    if (enabled) {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);
            Map fields = new HashMap();
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];
            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            fileUrl = currentPath + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    fileUrl = currentPath + "/" + newName;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } else {
                retVal = "202";
                errorMessage = "";
                if (debug)
                    System.out.println("Invalid file type: " + ext);
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
    }

    System.out.println("111111222111111111");
    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();
    if (debug)
        System.out.println("--- END DOPOST ---");
}

From source file:controller.FacebookServlet.java

public boolean doFilePost(HttpServletRequest request) {
    System.out.println("Do file post");
    DiskFileItemFactory fileUpload = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(fileUpload);
    if (request.getContentType() == null) {
        System.out.println("Content type null");
        return false;
    }/*from   w  w w.  jav  a 2 s.com*/
    if (!request.getContentType().startsWith("multipart/form-data")) {
        System.out.println("No comea com multipart");
        return false;
    }
    String diretorio = "C:\\Users\\BBEIRIGO\\Documents\\NetBeansProjects\\WebServiceFacebook\\src\\main\\webapp\\photos";

    System.out.println("DIRETORIO:" + diretorio);
    String filename = "file";
    String path = diretorio;
    List list;
    try {
        list = sfu.parseRequest(request);

        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            FileItem item = (FileItem) iterator.next();
            if (!item.isFormField()) {
                System.out.println("FIELD NAME:" + item.getFieldName());
                filename = item.getName();
                if ((filename != null) && (!filename.equals(""))) {
                    filename = (new File(filename)).getName();
                    item.write(new File(path + "/" + filename));
                }
            }
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return true;
}

From source file:AES.Controllers.FileController.java

@RequestMapping(value = "/upload", method = RequestMethod.GET)
public void upload(HttpServletResponse response, HttpServletRequest request,
        @RequestParam Map<String, String> requestParams) throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("Hello<br/>");

    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    if (!isMultipartContent) {
        out.println("You are not trying to upload<br/>");
        return;// w  w  w  . java 2  s.  c om
    }
    out.println("You are trying to upload<br/>");

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> fields = upload.parseRequest(request);
        out.println("Number of fields: " + fields.size() + "<br/><br/>");
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            out.println("No fields found");
            return;
        }
        out.println("<table border=\"1\">");
        while (it.hasNext()) {
            out.println("<tr>");
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                        + "<br/>STRING: " + fileItem.getString());
                out.println("</td>");
            } else {
                out.println("<td>file form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                        + "<br/>STRING: " + fileItem.getString() + "<br/>NAME: " + fileItem.getName()
                        + "<br/>CONTENT TYPE: " + fileItem.getContentType() + "<br/>SIZE (BYTES): "
                        + fileItem.getSize() + "<br/>TO STRING: " + fileItem.toString());
                out.println("</td>");
                String path = request.getSession().getServletContext().getRealPath("") + "\\uploads\\";
                //System.out.println(request.getSession().getServletContext().getRealPath(""));
                File f = new File(path + fileItem.getName());
                if (!f.exists())
                    f.createNewFile();
                fileItem.write(f);
            }
            out.println("</tr>");
        }
        out.println("</table>");
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (Exception ex) {
        Logger.getLogger(FileController.class.getName()).log(Level.SEVERE, null, ex);
    }
}