Adds a upload file section to the request
@param fieldName name attribute in &lt;input type="file" name="..." /&gt;
@param uploadFile a File to be uploaded
@throws IOException if problems
198755
public void addFilePart(final String fieldName, final File uploadFile)
        throws IOException
    {
        String fileName = uploadFile.getName();

        addFilePart(fieldName, new FileInputStream(uploadFile), fileName, URLConnection.guessContentTypeFromName(fileName));
    }
777379
private void uploadFilesToDFS(IStructuredSelection selection)
      throws InvocationTargetException, InterruptedException {

    // Ask the user which files to upload
    FileDialog dialog =
        new FileDialog(Display.getCurrent().getActiveShell(), SWT.OPEN
            | SWT.MULTI);
    dialog.setText("Select the local files to upload");
    dialog.open();

    List<File> files = new ArrayList<File>();
    for (String fname : dialog.getFileNames())
      files.add(new File(dialog.getFilterPath() + File.separator + fname));

    // TODO enable upload command only when selection is exactly one folder
    List<DFSFolder> folders = filterSelection(DFSFolder.class, selection);
    if (folders.size() >= 1)
      uploadToDFS(folders.get(0), files);
  }

  /**
   * Implement the import action (upload directory from the current machine
   * to HDFS)
   * 
   * @param object
   * @throws SftpException
   * @throws JSchException
   * @throws InvocationTargetException
   * @throws InterruptedException
   */
  private void uploadDirectoryToDFS(IStructuredSelection selection)
      throws InvocationTargetException, InterruptedException {

    // Ask the user which local directory to upload
    DirectoryDialog dialog =
        new DirectoryDialog(Display.getCurrent().getActiveShell(), SWT.OPEN
            | SWT.MULTI);
    dialog.setText("Select the local file or directory to upload");

    String dirName = dialog.open();
    final File dir = new File(dirName);
    List<File> files = new ArrayList<File>();
    files.add(dir);

    // TODO enable upload command only when selection is exactly one folder
    final List<DFSFolder> folders =
        filterSelection(DFSFolder.class, selection);
    if (folders.size() >= 1)
      uploadToDFS(folders.get(0), files);

  }

  private void uploadToDFS(final DFSFolder folder, final List<File> files)
      throws InvocationTargetException, InterruptedException {

    PlatformUI.getWorkbench().getProgressService().busyCursorWhile(
        new IRunnableWithProgress() {
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException {

            int work = 0;
            for (File file : files)
              work += computeUploadWork(file);

            monitor.beginTask("Uploading files to distributed file system",
                work);

            for (File file : files) {
              try {
                folder.upload(monitor, file);

              } catch (IOException ioe) {
                ioe.printStackTrace();
                MessageDialog.openError(null,
                    "Upload files to distributed file system",
                    "Upload failed.\n" + ioe);
              }
            }

            monitor.done();

            // Update the UI
            folder.doRefresh();
          }
        });
  }

  private void reconnect(IStructuredSelection selection) {
    for (DFSLocation location : filterSelection(DFSLocation.class, selection))
      location.reconnect();
  }

  private void disconnect(IStructuredSelection selection) {
    if (selection.size() != 1)
      return;

    Object first = selection.getFirstElement();
    if (!(first instanceof DFSLocationsRoot))
      return;

    DFSLocationsRoot root = (DFSLocationsRoot) first;
    root.disconnect();
    root.refresh();
  }

  /**
   * Implements the Download action from HDFS to the current machine
   * 
   * @param object
   * @throws SftpException
   * @throws JSchException
   * @throws InterruptedException
   * @throws InvocationTargetException
   */
  private void downloadFromDFS(IStructuredSelection selection)
      throws InvocationTargetException, InterruptedException {

    // Ask the user where to put the downloaded files
    DirectoryDialog dialog =
        new DirectoryDialog(Display.getCurrent().getActiveShell());
    dialog.setText("Copy to local directory");
    dialog.setMessage("Copy the selected files and directories from the "
        + "distributed filesystem to a local directory");
    String directory = dialog.open();

    if (directory == null)
      return;

    final File dir = new File(directory);
    if (!dir.exists())
      dir.mkdirs();

    if (!dir.isDirectory()) {
      MessageDialog.openError(null, "Download to local file system",
          "Invalid directory location: \"" + dir + "\"");
      return;
    }

    final List<DFSPath> paths = filterSelection(DFSPath.class, selection);

    PlatformUI.getWorkbench().getProgressService().busyCursorWhile(
        new IRunnableWithProgress() {
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException {

            int work = 0;
            for (DFSPath path : paths)
              work += path.computeDownloadWork();

            monitor
                .beginTask("Downloading files to local file system", work);

            for (DFSPath path : paths) {
              if (monitor.isCanceled())
                return;
              try {
                path.downloadToLocalDirectory(monitor, dir);
              } catch (Exception e) {
                // nothing we want to do here
                e.printStackTrace();
              }
            }

            monitor.done();
          }
        });
  }
55305
function (fieldname, file, filename) {
          const acceptedExtensions = strapi.api.upload.config.acceptedExtensions || [];
          if (acceptedExtensions[0] !== '*' && !_.contains(acceptedExtensions, path.extname(filename))) {
            this.status = 400;
            this.body = {
              message: 'Invalid file format ' + filename ? 'for this file' + filename : ''
            };
          }
        }
490643
public function setFileUpload(UploadedFile $file = null)
    {
        $propertyName = $this->getFileUploadPropertyName(__FUNCTION__);

        unset($this->fileUploads[$propertyName]);
        if ($file instanceof UploadedFile) {
            $this->fileUploads[$propertyName] = $file;
        }
    }
515853
public void addFile(String filename, String filePath) {
        int pathIndex = filePathList.indexOf(filePath);
        if (pathIndex == -1) {
            fileNameList.add(filename);
            filePathList.add(filePath);
        }
    }
118186
func (p *WebPage) UploadFile(selector, filename string) error {
	return p.ref.process.doJSON("POST", "/webpage/UploadFile", map[string]interface{}{"ref": p.ref.id, "selector": selector, "filename": filename}, nil)
}
1001097
@Override
    protected void uploadTusFiles() throws IOException, ProtocolException {
        setState(State.UPLOADING);
        while (uploads.size() > 0) {
            final TusUploader tusUploader;
            // don't recreate uploader if it already exists.
            // this is to avoid multiple connections being open. And to avoid some connections left unclosed.
            if (lastTusUploader != null) {
                tusUploader = lastTusUploader;
                lastTusUploader = null;
            } else {
                tusUploader = tusClient.resumeOrCreateUpload(uploads.get(0));
                if (getUploadChunkSize() > 0) {
                    tusUploader.setChunkSize(getUploadChunkSize());
                }
            }

            TusExecutor tusExecutor = new TusExecutor() {
                @Override
                protected void makeAttempt() throws ProtocolException, IOException {
                    while (state == State.UPLOADING) {
                        int chunkUploaded = tusUploader.uploadChunk();
                        if (chunkUploaded > 0) {
                            uploadedBytes += chunkUploaded;
                            listener.onUploadPogress(uploadedBytes, totalUploadSize);
                        } else {
                            // upload is complete
                            break;
                        }
                    }
                }
            };

            tusExecutor.makeAttempts();
            if (state != State.UPLOADING) {
                // if upload is paused, save the uploader so it can be reused on resume, then leave the method early.
                lastTusUploader = tusUploader;
                return;
            }

            // remove upload instance from list
            uploads.remove(0);
            tusUploader.finish();
        }

        setState(State.UPLOAD_COMPLETE);
    }
21911
@Override
  public synchronized void upload(File fileToUpload, String filename,
      String contents, String comment) throws Exception {
    this.upload(new FileInputStream(fileToUpload), filename, contents, comment);
  }
461741
public Path upload(final File localFile) throws IOException {

    if (!localFile.exists()) {
      throw new FileNotFoundException(localFile.getAbsolutePath());
    }

    final Path source = new Path(localFile.getAbsolutePath());
    final Path destination = new Path(this.path, localFile.getName());

    try {
      this.fileSystem.copyFromLocalFile(source, destination);
    } catch (final IOException ex) {
      LOG.log(Level.SEVERE, "Unable to upload " + source + " to " + destination, ex);
      throw ex;
    }

    LOG.log(Level.FINE, "Uploaded {0} to {1}", new Object[] {source, destination});

    return destination;
  }
872981
function uploadFile(file, next) {
    var uploadErr;

    self.uploadFile({
      source: file.source,
      target: file.target,
      server: options.server,
      keys: options.keys,
      tunnel: options.tunnel,
      remoteUser: options.remoteUser
    }).on('error', function (err) {
      if (!uploadErr) {
        uploadErr = true;
        next(err);
      }
    }).on('complete', function () {
      if (!uploadErr) {
        next();
      }
    });
  }
1020047
public void put(final File file, final String key, String token, final UpCompletionHandler complete,
                    final UploadOptions options) {
        final UpToken decodedToken = UpToken.parse(token);
        if (areInvalidArg(key, null, file, token, decodedToken, complete)) {
            return;
        }

        Zone z = config.zone;
        z.preQuery(token, new Zone.QueryHandler() {
            @Override
            public void onSuccess() {
                long size = file.length();
                if (size <= config.putThreshold) {
                    FormUploader.upload(client, config, file, key, decodedToken, complete, options);
                    return;
                }
                String recorderKey = config.keyGen.gen(key, file);
                final WarpHandler completionHandler = warpHandler(complete, file != null ? file.length() : 0);
                ResumeUploader uploader = new ResumeUploader(client, config, file, key,
                        decodedToken, completionHandler, options, recorderKey);

                AsyncRun.runInMain(uploader);
            }

            @Override
            public void onFailure(int reason) {
                final ResponseInfo info = ResponseInfo.isStatusCodeForBrokenNetwork(reason) ?
                        ResponseInfo.networkError(reason, decodedToken) :
                        ResponseInfo.invalidToken("invalid token");
                complete.complete(key, info, null);
            }
        });

    }
1200559
public boolean uploadConfigurationAndProfile(String fileName, String odoImport) {
        File file = new File(fileName);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntityBuilder.addPart("fileData", fileBody);
        multipartEntityBuilder.addTextBody("odoImport", odoImport);
        try {
            JSONObject response = new JSONObject(doMultipartPost(BASE_BACKUP_PROFILE + "/" + uriEncode(this._profileName) + "/" + this._clientId, multipartEntityBuilder));
            if (response.length() == 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }
925339
@Override
    public synchronized void addFile(File pFile, String pRelativePath) throws TTException, IOException {
        // LOGGER.info("Adding file " + pFile.getName());

        int readingAmount = 0;

        @SuppressWarnings("resource")
        FileChannel ch = new RandomAccessFile(pFile, "rw").getChannel();
        FileLock lock = null;

        while (lock == null) {
            try {
                lock = ch.tryLock();
            } catch (OverlappingFileLockException e) {
                // File is already locked in this thread or virtual machine
            }
        }

        // LOGGER.info("Filesize: " + ch.size());

        ByteBuffer buffer = ByteBuffer.allocate(FileData.FILENODESIZE);

        // LOGGER.debug("Successfully initialized byte source.");
        readingAmount += ch.read(buffer);

        // LOGGER.debug("First readAmount: " + readingAmount);
        if (readingAmount <= 0) {
            MetaKey key = new MetaKey(pRelativePath);
            MetaValue value = new MetaValue(FilelistenerReadTrx.emptyFileKey);
            getBucketTransaction().getMetaBucket().put(key, value);

            return;
        }

        long newKey = getBucketTransaction().incrementDataKey();

        if (fileExists(pRelativePath)) {
            removeFile(pRelativePath);
        }

        // Setting a new header file data
        MetaKey key = new MetaKey(pRelativePath);
        MetaValue value = new MetaValue(newKey);

        // And adding it to the meta map
        // LOGGER.debug("Metakeypair setup");
        getBucketTransaction().getMetaBucket().put(key, value);

        // Creating and setting the headerdata.
        FileData headerData = new FileData(newKey, buffer.array(), false);

        getBucketTransaction().setData(headerData);

        // Creating and setting following datas based on the file size.
        FileData data;

        int currentReadingAmount = 0;
        // LOGGER.info("Iterating file content");
        while ((currentReadingAmount = ch.read(buffer = ByteBuffer.allocate(FileData.FILENODESIZE))) > 0) {
            // LOGGER.debug("Curr. read amount: " + currentReadingAmount);
            byte[] slice = Arrays.copyOf(buffer.array(), currentReadingAmount);

            long dataKey = getBucketTransaction().incrementDataKey();
            data = new FileData(dataKey, slice, false);

            getBucketTransaction().setData(data);

            readingAmount += currentReadingAmount;
        }

        ByteArrayDataOutput size = ByteStreams.newDataOutput();
        size.writeInt(readingAmount);

        data = new FileData(getBucketTransaction().incrementDataKey(), size.toByteArray(), true);

        getBucketTransaction().setData(data);

        Preconditions.checkArgument(getBucketTransaction().getData(newKey) != null);
        lock.release();
        ch.close();
    }
108579
public void doUpload(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException
    {
        MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/tmp");
        request.setAttribute("org.eclipse.multipartConfig", multipartConfigElement);
        if (!common.checkPost(request, response)) return;
        User user = common.requireLoggedInUser(request, response);
        if (user == null) return;

        DbxClientV2 dbxClient = requireDbxClient(request, response, user);
        if (dbxClient == null) return;

        try {
            request.getParts();  // Just call getParts() to trigger the too-large exception.
        }
        catch (IllegalStateException ex) {
            response.sendError(400, "Request too large");
            return;
        }

        String targetFolder = slurpUtf8Part(request, response, "targetFolder", 1024);
        if (targetFolder == null) return;

        Part filePart = request.getPart("file");
        if (filePart == null) {
            response.sendError(400, "Field \"file\" is missing.");
            return;
        }
        String fileName = filePart.getName();
        if (fileName == null) {
            response.sendError(400, "Field \"file\" has no name.");
            return;
        }

        // Upload file to Dropbox
        String fullTargetPath = targetFolder + "/" + fileName;
        FileMetadata metadata;
        try {
            metadata = dbxClient.files()
                .upload(fullTargetPath)
                .uploadAndFinish(filePart.getInputStream());
        }
        catch (DbxException ex) {
            common.handleDbxException(response, user, ex, "upload(" + jq(fullTargetPath) + ", ...)");
            return;
        }
        catch (IOException ex) {
            response.sendError(400, "Error getting file data from you.");
            return;
        }

        // Display uploaded file metadata.
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));

        out.println("<html>");
        out.println("<head><title>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</title></head>");
        out.println("<body>");
        out.println("<h2>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</h2>");
        out.println("<pre>");
        out.print(escapeHtml4(metadata.toStringMultiline()));
        out.println("</pre>");
        out.println("</body>");
        out.println("</html>");

        out.flush();
    }
1220939
public boolean upload(String path, String fileName, File file) {
		try (InputStream in = FileUtil.getInputStream(file)) {
			return upload(path, fileName, in);
		} catch (IOException e) {
			throw new FtpException(e);
		}
	}
346851
protected function imageUpload($field, UploadedFile $file)
    {
        if (UPLOAD_ERR_OK == $file->getError()) {
            $asserts = $this->getAsserts()[$field];

            foreach ($asserts as $assert) {
                // Detect image size constraints and resize accordingly
                if ($assert instanceof Image) {
                    $path = $file->getPathname();
                    $pathWithExtension = $path.'.'.$file->guessExtension();
                    rename($path, $pathWithExtension);

                    // ImageWorkshop relies on the file's extension for encoding
                    try {
                        $this->resize($pathWithExtension, $assert->maxWidth, $assert->maxHeight);
                    } catch (ImageWorkshopException $e) {
                    }

                    rename($pathWithExtension, $path);
                }
            }
        }
    }
492468
public void addFile(String filename) {
        synchronized (files) {
            if (!files.contains(filename)) {
                files.add(filename);
            }
        }
    }