Search in sources :

Example 6 with DiskFileItem

use of org.apache.commons.fileupload.disk.DiskFileItem in project ma-modules-public by infiniteautomation.

the class ImageUploadServlet method doPost.

@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (ServletFileUpload.isMultipartContent(request)) {
        User user = Common.getUser(request);
        GraphicalView view = GraphicalViewsCommon.getUserEditView(user);
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        // Fail if we don't have permissions for this
        if (!Permissions.hasPermission(user, SystemSettingsDao.getValue(GraphicalViewUploadPermissionDefinition.PERMISSION))) {
            // The GraphicalViewDwr.clearBackground() method will notify the user of a failure so we can ignore them here
            return;
        }
        List<FileItem> items;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        for (FileItem item : items) {
            if ("backgroundImage".equals(item.getFieldName())) {
                final DiskFileItem diskItem = (DiskFileItem) item;
                try {
                    // will throw IOException if not supported or null if not an image
                    if (ImageIO.read(diskItem.getInputStream()) != null) {
                        // Create the path to the upload directory.
                        File dir = GraphicalViewsCommon.getUploadDir();
                        // Create the image file name.
                        String filename = GraphicalViewsCommon.getNextImageFilename(dir, diskItem.getName());
                        // Save the file.
                        FileOutputStream fos = new FileOutputStream(new File(dir, filename));
                        StreamUtils.transfer(diskItem.getInputStream(), fos);
                        fos.close();
                        view.setBackgroundFilename(ImageUploadServletDefinition.IMAGE_DIR + "/" + filename);
                    } else {
                    // Unsupported File Type
                    }
                } catch (Exception e) {
                // Unsupported Image Type
                }
            }
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) User(com.serotonin.m2m2.vo.User) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) GraphicalView(com.serotonin.m2m2.gviews.GraphicalView) FileOutputStream(java.io.FileOutputStream) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) IOException(java.io.IOException) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 7 with DiskFileItem

use of org.apache.commons.fileupload.disk.DiskFileItem in project xwiki-platform by xwiki.

the class FileUploadPlugin method loadFileList.

/**
 * Loads the list of uploaded files in the context if there are any uploaded files.
 *
 * @param uploadMaxSize Maximum size of the uploaded files.
 * @param uploadSizeThreashold Threashold over which the file data should be stored on disk, and not in memory.
 * @param tempdir Temporary directory to store the uploaded files that are not kept in memory.
 * @param context Context of the request.
 * @throws XWikiException if the request could not be parsed, or the maximum file size was reached.
 * @see FileUploadPluginApi#loadFileList(long, int, String)
 */
public void loadFileList(long uploadMaxSize, int uploadSizeThreashold, String tempdir, XWikiContext context) throws XWikiException {
    LOGGER.debug("Loading uploaded files");
    // Continuing would empty the list.. We need to stop.
    if (context.get(FILE_LIST_KEY) != null) {
        LOGGER.debug("Called loadFileList twice");
        return;
    }
    // Get the FileUpload Data
    // Make sure the factory only ever creates file items which will be deleted when the jvm is stopped.
    DiskFileItemFactory factory = new DiskFileItemFactory() {

        @Override
        public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) {
            try {
                final DiskFileItem item = (DiskFileItem) super.createItem(fieldName, contentType, isFormField, fileName);
                // Needed to make sure the File object is created.
                item.getOutputStream();
                return item;
            } catch (IOException e) {
                String path = System.getProperty("java.io.tmpdir");
                if (super.getRepository() != null) {
                    path = super.getRepository().getPath();
                }
                throw new RuntimeException("Unable to create a temporary file for saving the attachment. " + "Do you have write access on " + path + "?");
            }
        }
    };
    factory.setSizeThreshold(uploadSizeThreashold);
    if (tempdir != null) {
        File tempdirFile = new File(tempdir);
        if (tempdirFile.mkdirs() && tempdirFile.canWrite()) {
            factory.setRepository(tempdirFile);
        }
    }
    // TODO: Does this work in portlet mode, or we must use PortletFileUpload?
    FileUpload fileupload = new ServletFileUpload(factory);
    RequestContext reqContext = new ServletRequestContext(context.getRequest().getHttpServletRequest());
    fileupload.setSizeMax(uploadMaxSize);
    try {
        @SuppressWarnings("unchecked") List<FileItem> list = fileupload.parseRequest(reqContext);
        if (list.size() > 0) {
            LOGGER.info("Loaded " + list.size() + " uploaded files");
        }
        // We store the file list in the context
        context.put(FILE_LIST_KEY, list);
    } catch (FileUploadBase.SizeLimitExceededException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE, "Exception uploaded file");
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_UPLOAD_PARSE_EXCEPTION, "Exception while parsing uploaded file", e);
    }
}
Also used : ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) XWikiException(com.xpn.xwiki.XWikiException) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUploadBase(org.apache.commons.fileupload.FileUploadBase) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) File(java.io.File) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUpload(org.apache.commons.fileupload.FileUpload) XWikiException(com.xpn.xwiki.XWikiException) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 8 with DiskFileItem

use of org.apache.commons.fileupload.disk.DiskFileItem in project xwiki-platform by xwiki.

the class XWikiAttachmentContent method getNewFileItem.

/**
 * @return a new FileItem for temporarily storing attachment content.
 * @since 4.2M3
 */
private static FileItem getNewFileItem() {
    final Environment env = Utils.getComponent(Environment.class);
    final File dir = new File(env.getTemporaryDirectory(), "attachment-cache");
    try {
        if (!dir.mkdirs() && !dir.exists()) {
            throw new UnexpectedException("Failed to create directory for attachments " + dir);
        }
        final DiskFileItem dfi = new DiskFileItem(null, null, false, null, 10000, dir);
        // This causes the temp file to be created.
        dfi.getOutputStream().close();
        return dfi;
    } catch (IOException e) {
        throw new UnexpectedException("Failed to create new attachment temporary file.", e);
    }
}
Also used : UnexpectedException(org.xwiki.store.UnexpectedException) Environment(org.xwiki.environment.Environment) IOException(java.io.IOException) File(java.io.File) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Aggregations

DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)8 File (java.io.File)6 IOException (java.io.IOException)5 FileItem (org.apache.commons.fileupload.FileItem)5 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)3 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)3 FileOutputStream (java.io.FileOutputStream)2 BasicDBObject (com.mongodb.BasicDBObject)1 GraphicalView (com.serotonin.m2m2.gviews.GraphicalView)1 User (com.serotonin.m2m2.vo.User)1 XWikiException (com.xpn.xwiki.XWikiException)1 OutputStream (java.io.OutputStream)1 ArrayList (java.util.ArrayList)1 SneakyThrows (lombok.SneakyThrows)1 lombok.val (lombok.val)1 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)1 FileUpload (org.apache.commons.fileupload.FileUpload)1 FileUploadBase (org.apache.commons.fileupload.FileUploadBase)1 FileUploadException (org.apache.commons.fileupload.FileUploadException)1 RequestContext (org.apache.commons.fileupload.RequestContext)1