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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:com.adanac.module.blog.servlet.UploadImage.java

@Override
protected void service() throws ServletException, IOException {
    HttpServletRequest request = getRequest();
    String path = null;/*from   w w w.  j ava2s .c o m*/
    DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024,
            new File(Configuration.getContextPath("temp")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(3 * 1024 * 1024);
    try {
        List<FileItem> items = upload.parseRequest(request);
        FileItem fileItem = null;
        if (items != null && items.size() > 0 && StringUtils.isNotBlank((fileItem = items.get(0)).getName())) {
            String fileName = fileItem.getName();
            if (!fileName.endsWith(".jpg") && !fileName.endsWith(".gif") && !fileName.endsWith(".png")) {
                writeText("format_error");
                return;
            }
            path = ImageUtil.generatePath(fileItem.getName());
            IOUtil.copy(fileItem.getInputStream(), Configuration.getContextPath(path));
            fileItem.delete();
            writeText(Configuration.getSiteUrl(path));
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    }
}

From source file:es.ucm.fdi.dalgs.topic.service.TopicService.java

@PreAuthorize("hasRole('ROLE_ADMIN')")
@Transactional(readOnly = false)//from w w  w .  ja v a2s  . c  o  m
public ResultClass<Boolean> uploadCSV(UploadForm upload, Long id_module, Long id_degree, Locale locale) {
    ResultClass<Boolean> result = new ResultClass<>();
    if (!upload.getFileData().isEmpty()) {
        CsvPreference prefers = new CsvPreference.Builder(upload.getQuoteChar().charAt(0),
                upload.getDelimiterChar().charAt(0), upload.getEndOfLineSymbols()).build();

        List<Topic> list = null;
        try {
            FileItem fileItem = upload.getFileData().getFileItem();
            TopicCSV topicUpload = new TopicCSV();

            Module m = serviceModule.getModule(id_module, id_degree).getSingleElement();
            list = topicUpload.readCSVTopicToBean(fileItem.getInputStream(), upload.getCharset(), prefers, m);
            if (list == null) {
                result.setHasErrors(true);
                result.getErrorsList().add(messageSource.getMessage("error.params", null, locale));
            } else {
                result.setSingleElement(repositoryTopic.persistListTopics(list));
                if (result.getSingleElement()) {
                    for (Topic c : list) {
                        Topic aux = repositoryTopic.existByCode(c.getInfo().getCode(), id_module);
                        result.setSingleElement(result.getSingleElement()
                                && manageAclService.addACLToObject(aux.getId(), aux.getClass().getName()));

                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.setSingleElement(false);
        }
    } else {
        result.setHasErrors(true);
        result.getErrorsList().add(messageSource.getMessage("error.fileEmpty", null, locale));
    }
    return result;
}

From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java

/**
 * Processes an uploaded file and stores it in MongoDB.
 * @param item file item from the parsed servlet request
 * @param currentId ID for the current MongoDB object for the advice
 * @return file name//from   w  w  w  .  j  a  v  a 2  s  . co m
 * @throws IOException 
 */
private String processUploadedFile(FileItem item, String currentId) throws IOException {
    System.out.println("file: size=" + item.getSize() + " name:" + item.getName());
    GridFS gridfs = mi.getImagesFS();
    String filename = currentId + ":" + item.getFieldName() + "_" + item.getName();
    gridfs.remove(filename);
    GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream());
    gfsFile.setFilename(filename);
    gfsFile.setContentType(item.getContentType());
    gfsFile.save();
    return filename;
}

From source file:com.app.uploads.ImageTest.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w w  . jav  a2 s .  c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String type = "";
    CallableStatement pro;

    String UPLOAD_DIRECTORY = getServletContext().getRealPath("\\uploads\\");
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                String name = "";
                List<FileItem> multiparts;
                multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    } else if (item.isFormField()) {
                        String fiel = item.getFieldName();
                        InputStream is = item.getInputStream();
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        type = new String(b);
                    }

                }

                //File uploaded successfully
                Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName,
                        Dir.PassWord);
                pro = connect.prepareCall("{call STILL_INSERT_TEST(?,?)}");
                pro.setInt(1, 2);
                pro.setString(2, name);
                pro.executeQuery();
                pro.close();
                connect.close();
                if (name != null) {
                    request.setAttribute("type", type);
                    request.setAttribute("success", "ok");
                }
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }

        request.getRequestDispatcher("/SearchEngine.jsp").forward(request, response);
    } finally {
        out.close();
    }
}

From source file:com.xpn.xwiki.plugin.fileupload.FileUploadPlugin.java

/**
 * Allows to retrieve the contents of an uploaded file as a stream. {@link #loadFileList(XWikiContext)} needs to be
 * called beforehand./*from   w  w w .  ja  va 2  s . c o m*/
 * 
 * @param formfieldName The name of the form field.
 * @param context Context of the request.
 * @return a InputStream on the file content
 * @throws IOException if I/O problem occurs
 * @since 2.3M2
 */
public InputStream getFileItemInputStream(String formfieldName, XWikiContext context) throws IOException {
    FileItem fileitem = getFile(formfieldName, context);

    if (fileitem == null) {
        return null;
    }

    return fileitem.getInputStream();
}

From source file:com.baobao121.baby.common.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 * //from   w  w  w . jav a2s . c  o  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 currentPath = "";
    String currentDirPath = "";
    String typeStr = request.getParameter("Type");
    UserCommonInfo info = null;
    info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.USER_COMMON_INFO);
    if (info == null) {
        info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.ADMIN_INFO);
    }
    currentPath = baseDir + "images/";
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    if (info.getObjectTableName() == null || info.getObjectTableName().equals("")) {
        currentPath += "admin/";
    } else {
        if (info.getObjectTableName().equals(SystemConstant.BABY_INFO_TABLE_NAME)) {
            currentPath += "babyInfo/";
        }
        if (info.getObjectTableName().equals(SystemConstant.KG_TEACHER_INFO_TABLE_NAME)) {
            currentPath += "teacherInfo/";
        }
    }
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    currentPath += info.getId();
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    if (debug)
        System.out.println(currentDirPath);

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

    if (enabled) {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            upload.setHeaderEncoding("utf-8");
            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();
            InputStream is = uplFile.getInputStream();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];
            Calendar calendar = Calendar.getInstance();
            String nameWithoutExt = String.valueOf(calendar.getTimeInMillis());
            ;
            String ext = getExtension(fileName);
            fileName = nameWithoutExt + "." + ext;
            fileUrl = currentPath + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                FileOutputStream desc = new FileOutputStream(currentDirPath + "/" + fileName);
                changeDimension(is, desc, 450, 1000);
                if (info.getObjectTableName() != null && !info.getObjectTableName().equals("")) {
                    Photo photo = new Photo();
                    photo.setPhotoName(fileName);
                    PhotoAlbum album = babyAlbumDao.getMAlbumByUser(info.getId(), info.getObjectTableName());
                    if (album.getId() != null) {
                        Long albumId = album.getId();
                        photo.setPhotoAlbumId(albumId);
                        photo.setPhotoLink(fileUrl);
                        photo.setDescription("");
                        photo.setReadCount(0L);
                        photo.setCommentCount(0L);
                        photo.setReadPopedom("1");
                        photo.setCreateTime(DateUtil.getCurrentDateTimestamp());
                        photo.setModifyTime(DateUtil.getCurrentDateTimestamp());
                        babyPhotoDao.save(photo);
                        babyAlbumDao.updateAlbumCount(albumId);
                    }
                }
            } else {
                retVal = "202";
                errorMessage = "";
                if (debug)
                    System.out.println("?: " + ext);
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "??";
    }

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

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:de.zib.gndms.kit.monitor.GroovyMonitor.java

/**
 * Processing of single parts./*from  w w  w . j a  va  2s . c om*/
 * <br />
 *
 * Converts non-file parts into string streams and handles base64 decoding.
 *
  * @param b64 if true, the content is asumed to be encoded in base64
  * @param args args to the part/script
  * @param part @throws IOException
  */
private synchronized void handlePart(boolean b64, @NotNull String args, @NotNull FileItem part)
        throws IOException {
    if (!part.isFormField()) {
        InputStream in = part.getInputStream();
        handleStream(b64, args, in);
    } else {
        final String val = part.getString();
        final InputStream valStream = new ByteArrayInputStream(val.getBytes("utf8"));
        try {
            handleStream(b64, args, valStream);
        } finally {
            valStream.close();
        }
    }
}

From source file:com.softwarementors.extjs.djn.test.ManualFormUploadSupportTest.java

@DirectFormPostMethod
public Result djnform_test_sendFilesManually(Map<String, String> formParameters,
        Map<String, FileItem> fileFields) {
    assert formParameters != null;
    assert fileFields != null;

    Result r = new Result();
    FileItem file1 = fileFields.get("fileUpload1");
    FileItem file2 = fileFields.get("fileUpload2");
    if (fileFields.size() != 2 || file1 == null || file2 == null) {
        throw new DirectTestFailedException("Unexpected error receiving file fields");
    }//from  w  w w . j  a  v a  2 s.c  o  m

    try {
        r.file1Field = file1.getFieldName();
        r.file1Name = file1.getName();
        if (!r.file1Name.equals("")) {
            r.file1Text = IOUtils.toString(file1.getInputStream());
            file1.getInputStream().close();
        }

        r.file2Field = file2.getFieldName();
        r.file2Name = file2.getName();
        if (!r.file2Name.equals("")) {
            r.file2Text = IOUtils.toString(file2.getInputStream());
            file2.getInputStream().close();
        }
    } catch (IOException e) {
        throw new DirectTestFailedException("Test failed", e);
    }

    return r;
}

From source file:at.ac.tuwien.dsg.depic.depictool.uploader.InputSpecificationUploader.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w  ww  .  j av  a2 s. c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //process only if its multipart content

    String eDaaSName = "";
    DBType dbType = null;
    String qor = "";
    String daw = "";

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    // item.write( new File(UPLOAD_DIRECTORY + File.separator + name));

                    InputStream filecontent = item.getInputStream();

                    StringWriter writer = new StringWriter();
                    IOUtils.copy(filecontent, writer, "UTF-8");
                    String str = writer.toString();

                    //     String log = "item: " + item.getFieldName() + " - file name: " + name + " - content: " + str;

                    if (item.getFieldName().equals("qor")) {

                        qor = str;
                    }

                    if (item.getFieldName().equals("dataAnalyticsFunction")) {

                        daw = str;
                    }

                    //    Logger.getLogger(InputSpecificationUploader.class.getName()).log(Level.INFO, log);

                } else {

                    String fieldname = item.getFieldName();
                    String fieldvalue = item.getString();
                    if (fieldname.equals("edaas")) {
                        eDaaSName = fieldvalue;
                    }

                    if (fieldname.equals("dbtype")) {
                        String typeStr = fieldvalue;

                        if (typeStr.equals(DBType.MYSQL.getDBType())) {
                            dbType = DBType.MYSQL;
                        } else if (typeStr.equals(DBType.CASSANDRA.getDBType())) {
                            dbType = DBType.CASSANDRA;
                        }
                    }

                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    String log = "edaas: " + eDaaSName;
    log = log + "dbType: " + dbType + "\n";
    log = log + "qor: " + qor + "\n";
    log = log + "daf: " + daw + "\n";
    log = log + "" + "\n";

    QoRModel qoRModel = YamlUtils.unmarshallYaml(QoRModel.class, qor);
    DataAnalyticsFunction dataAnalyticsFunction = new DataAnalyticsFunction(eDaaSName,
            qoRModel.getDataAssetForm(), dbType, daw);

    Logger.getLogger(InputSpecificationUploader.class.getName()).log(Level.INFO, log);

    ElasticProcessRepositoryManager eprm = new ElasticProcessRepositoryManager(
            getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

    String dafStr = "";

    try {
        dafStr = JAXBUtils.marshal(dataAnalyticsFunction, DataAnalyticsFunction.class);
    } catch (JAXBException ex) {
        Logger.getLogger(InputSpecificationUploader.class.getName()).log(Level.SEVERE, null, ex);
    }

    eprm.insertDaaS(eDaaSName);
    eprm.storeDAF(eDaaSName, dafStr);
    eprm.storeQoR(eDaaSName, qor);
    eprm.storeDBType(eDaaSName, dbType.getDBType());

    Generator generator = new Generator(dataAnalyticsFunction, qoRModel);
    generator.startGenerator();

    //  

    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

From source file:com.kunal.NewServlet2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  ww  .ja v a 2 s  .co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (ServletFileUpload.isMultipartContent(request)) {

        try {
            HttpSession session = request.getSession();
            String V_Str_Id = (String) session.getAttribute("VSID");
            String containerName = V_Str_Id;
            //String fileName = "Ad2";
            String userId = "7f7a82c6a2464a45b0ea5b7c65c90f38";
            String password = "lM_EC#0a7U})SE-.";
            String auth_url = "https://lon-identity.open.softlayer.com" + "/v3";
            String domain = "1090141";
            String project = "object_storage_e32c650b_e512_4e44_aeb8_c49fdf1de69f";
            Identifier domainIdent = Identifier.byName(domain);
            Identifier projectIdent = Identifier.byName(project);

            OSClient os = OSFactory.builderV3().endpoint(auth_url).credentials(userId, password)
                    .scopeToProject(projectIdent, domainIdent).authenticate();

            SwiftAccount account = os.objectStorage().account().get();
            ObjectStorageService objectStorage = os.objectStorage();
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    System.out.println(name);
                    // item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    String etag = os.objectStorage().objects().put(containerName, name,
                            Payloads.create(item.getInputStream()));
                    System.out.println(etag);
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request.getRequestDispatcher("/Pre_Installation.jsp").forward(request, response);

}