Handling file upload to server
543634
function fileUpload(fileURI, serverURI, fileUploadOptions) {
  var deferred = q.defer();
  var transfer = new FileTransfer();
  transfer.upload(fileURI, serverURI, function uploadSuccess(response) {
    deferred.resolve(response);
  }, function uploadFailure(error) {
    deferred.reject(error);
  }, fileUploadOptions);
  return deferred.promise;
}
1334824
def _handle_files(self, data):
        """"""

        initial = data.get("set", False)
        files = data["files"]
        for f in files:
            try:
                fobj = File(
                    self.room,
                    self.conn,
                    f[0],
                    f[1],
                    type=f[2],
                    size=f[3],
                    expire_time=int(f[4]) / 1000,
                    uploader=f[6].get("nick") or f[6].get("user"),
                )
                self.room.filedict = fobj.fid, fobj
                if not initial:
                    self.conn.enqueue_data("file", fobj)
            except Exception:
                import pprint

                LOGGER.exception("bad file")
                pprint.pprint(f)
        if initial:
            self.conn.enqueue_data("initial_files", self.room.files)
197316
def upload_file_handle(
            self,
            bucket: str,
            key: str,
            src_file_handle: typing.BinaryIO,
            content_type: str=None,
            metadata: dict=None):
        
        raise NotImplementedError()
519387
protected void handleFileUploadRequest(final WMultiFileWidget widget, final XmlStringBuilder xml, final String uploadId) {

		FileWidgetUpload file = widget.getFile(uploadId);
		if (file == null) {
			throw new SystemException("Invalid file id [" + uploadId + "] to render uploaded response.");
		}
		int idx = widget.getFiles().indexOf(file);
		FileWidgetRendererUtil.renderFileElement(widget, xml, file, idx);
	}
504922
function ftpPut(inFilename, cb) {
    var fileUrl = '';
    if (/\//.test(inFilename)) {
      fileUrl = inFilename;
      inFilename = inFilename.split('/').slice(-1)[0];
    } else {
      fileUrl = localRoot + path.sep + currPath + path.sep + inFilename;
    }
    var fileData = fs.readFileSync(fileUrl);
    ftp.put(inFilename, fileData, function(err) {
      if (err) {
        log.error('Cannot upload file: ' + inFilename + ' --> ' + err);
        cb(err);
      } else {
        log.ok('Uploaded file: ' + inFilename.green + ' to: ' + ('/' + remoteRoot + '/' + currPath).yellow);
        cb(null);
      }
    });
  }
811991
def slice_upload(cookie, data):
    '''
    '''
    url = ''.join([
        const.PCS_URL_C,
        'file?method=upload&type=tmpfile&app_id=250528',
        '&', cookie.sub_output('BDUSS'),
    ])
    fields = []
    files = [('file', ' ', data)]
    headers = {'Accept': const.ACCEPT_HTML,'Origin': const.PAN_URL}
    req = net.post_multipart(url, headers, fields, files)
    if req:
        return json.loads(req.data.decode())
    else:
        return None
1205837
protected function handleUpload()
    {
        $this->uploadedField = array_keys($_FILES)[0];
        //check if any uploaded file for a defined field
        $this->uploadOk = $this->checkUpload();
        if(!$this->uploadOk) {
            return;
        }
        //exec upload
        $this->uploadOk = $this->uploadFields[$this->uploadedField]->handleUpload($this->uploader);
        if(!$this->uploadOk) {
            return;
        }
        //outputs post processing
        $outputs = $this->uploadFields[$this->uploadedField]->getOutputsFiles();
        foreach($this->uploadFieldsDefinitions[$this->uploadedField]['outputs'] as $output => $outputDefinition) {
            if(isset($outputDefinition['processor'])) {
                $this->{$outputDefinition['processor']}($outputs[$output]['path']);
            }
        }
    }
796614
def handle_POST(self):
        
        self.send_response(404)
        self.end_headers()
        self.wfile.write('not found'.encode('utf8'))
516212
@Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Context context =
                ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
                                           request);
        try {
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();

            // Parse the request, looking for "file"
            InputStream in = null;
            FileItemIterator iter = upload.getItemIterator(request);
            while (in == null && iter.hasNext()) {
                FileItemStream item = iter.next();
                logger.info("Got next item: isFormField={} fieldName={}", item.isFormField(), item.getFieldName());
                if (!item.isFormField() && item.getFieldName().equals("file")) {
                    in = item.openStream();
                }
            }
            if (in == null) {
                sendResponse(HttpServletResponse.SC_BAD_REQUEST,
                             "No data sent.",
                             response);
            } else {
                sendResponse(HttpServletResponse.SC_CREATED,
                             m_management.putTempStream(context, in),
                             response);
            }
        } catch (AuthzException ae) {
            throw RootException.getServletException(ae,
                                                    request,
                                                    "Upload",
                                                    EMPTY_STRING_ARRAY);
        } catch (Exception e) {
            e.printStackTrace();
            sendResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e
                    .getClass().getName()
                    + ": " + e.getMessage(), response);
        }
    }
1063645
def upload_simple(self, fd, filename, folder_key=None, path=None,
                      filedrop_key=None, action_on_duplicate=None,
                      mtime=None, file_size=None, file_hash=None):
        
        action = 'upload/simple'

        params = QueryParams({
            'folder_key': folder_key,
            'path': path,
            'filedrop_key': filedrop_key,
            'action_on_duplicate': action_on_duplicate,
            'mtime': mtime
        })

        headers = QueryParams({
            'X-Filesize': str(file_size),
            'X-Filehash': file_hash,
            'X-Filename': filename.encode('utf-8')
        })

        upload_info = {
            "fd": fd,
        }

        return self.request(action, params, action_token_type="upload",
                            upload_info=upload_info, headers=headers)
69999
function(selector, filename, done) {
    this.debug('Upload ' + filename + ' to ' + selector);
    getPage(function(page) {
      page.uploadFile(selector, filename, done);
    });
      done();
  }
1135439
protected function handlePOST()
    {
        $extract = $this->request->getParameterAsBool('extract', false);
        $clean = $this->request->getParameterAsBool('clean', false);
        $checkExist = $this->request->getParameterAsBool('check_exist', false);

        if (empty($this->filePath)) {
            $fileNameHeader = str_to_utf8($this->request->getHeader('X-File-Name'));
            $folderNameHeader = str_to_utf8($this->request->getHeader('X-Folder-Name'));
            $fileUrl = filter_var($this->request->getParameter('url', ''), FILTER_SANITIZE_URL);

            if (!empty($fileNameHeader)) {
                // html5 single posting for file create
                $result = $this->handleFileContent(
                    $this->folderPath,
                    $fileNameHeader,
                    $this->request->getContent(),
                    $this->request->getContentType(),
                    $extract,
                    $clean,
                    $checkExist
                );
            } elseif (!empty($folderNameHeader)) {
                // html5 single posting for folder create
                $fullPathName = $this->folderPath . $folderNameHeader;
                $content = $this->request->getPayloadData();
                $this->driver->createFolder($this->container, $fullPathName, $content);
                $result = ['name' => $folderNameHeader, 'path' => $fullPathName];
            } elseif (!empty($fileUrl)) {
                // upload a file from a url, could be expandable zip
                $tmpName = null;
                $newFileName = $this->request->input('filename', '');
                try {
                    $tmpName = FileUtilities::importUrlFileToTemp($fileUrl);
                    $result = $this->handleFile(
                        $this->folderPath,
                        $newFileName,
                        $tmpName,
                        '',
                        $extract,
                        $clean,
                        $checkExist
                    );
                    @unlink($tmpName);
                } catch (\Exception $ex) {
                    if (!empty($tmpName)) {
                        @unlink($tmpName);
                    }
                    throw $ex;
                }
            } elseif (null !== $uploadedFiles = $this->request->getFile('files')) {
                if (Arr::isAssoc($uploadedFiles)) { //Single file upload
                    $uploadedFiles = [$uploadedFiles];
                }
                $result = $this->handleFolderContentFromFiles($uploadedFiles, $extract, $clean, $checkExist);
                $result = ResourcesWrapper::cleanResources($result);
            } else {
                // possibly xml or json post either of files or folders to create, copy or move
                if (!empty($data = ResourcesWrapper::unwrapResources($this->getPayloadData()))) {
                    $result = $this->handleFolderContentFromData($data, $extract, $clean, $checkExist);
                    $result = ResourcesWrapper::cleanResources($result);
                } else {
                    // create folder from resource path
                    $this->driver->createFolder($this->container, $this->folderPath);
                    $result = ['name' => basename($this->folderPath), 'path' => $this->folderPath];
                }
            }
        } else {
            // create the file
            // possible file handling parameters
            $name = basename($this->filePath);
            $path = (false !== strpos($this->filePath, '/')) ? dirname($this->filePath) : '';
            $files = $this->request->getFile('files');

            if (empty($files)) {
                // direct load from posted data as content
                // or possibly xml or json post of file properties create, copy or move
                $result = $this->handleFileContent(
                    $path,
                    $name,
                    $this->request->getContent(),
                    $this->request->getContentType(),
                    $extract,
                    $clean,
                    $checkExist
                );
            } else {
                if (Arr::isAssoc($files)) { // Single file upload
                    $files = [$files];
                }
                if (1 < count($files)) {
                    throw new BadRequestException("Multiple files uploaded to a single REST resource '$name'.");
                }
                $file = array_get($files, 0);
                if (empty($file)) {
                    throw new BadRequestException("No file uploaded to REST resource '$name'.");
                }
                $error = $file['error'];
                if (UPLOAD_ERR_OK == $error) {
                    $result = $this->handleFile(
                        $path,
                        $name,
                        $file["tmp_name"],
                        $file['type'],
                        $extract,
                        $clean,
                        $checkExist
                    );
                } else {
                    throw new InternalServerErrorException("Failed to upload file $name.\n$error");
                }
            }
        }

        return ResponseFactory::create($result, null, ServiceResponseInterface::HTTP_CREATED);
    }
62181
def upload_file(client, bucket, local_path, remote_path, overwrite=False):
    """"""
    bucket = client.get_bucket(bucket)
    blob = storage.Blob(remote_path, bucket)
    if (not overwrite) and blob.exists():
        raise Conflict('File/object already exists on the bucket!')
    blob.upload_from_filename(local_path)
509524
def save(self):
        """"""
        try:
            response = requests.post(self._upload_url,
                                     auth=self.jss.session.auth,
                                     verify=self.jss.session.verify,
                                     files=self.resource)
        except JSSPostError as error:
            if error.status_code == 409:
                raise JSSPostError(error)
            else:
                raise JSSMethodNotAllowedError(self.__class__.__name__)

        if response.status_code == 201:
            if self.jss.verbose:
                print "POST: Success"
                print response.text.encode("utf-8")
        elif response.status_code >= 400:
            error_handler(JSSPostError, response)
1331742
protected function handle_file_upload() {
        global $CFG;

        // Add the file to a draft file area.
        $draftitemid = file_get_unused_draft_itemid();
        $maxbytes = get_user_max_upload_file_size($this->context, $CFG->maxbytes, $this->course->maxbytes);
        $types = $this->dnduploadhandler->get_handled_file_types($this->module->name);
        $repo = repository::get_instances(array('type' => 'upload', 'currentcontext' => $this->context));
        if (empty($repo)) {
            throw new moodle_exception('errornouploadrepo', 'moodle');
        }
        $repo = reset($repo); // Get the first (and only) upload repo.
        $details = $repo->process_upload(null, $maxbytes, $types, '/', $draftitemid);
        if (empty($this->displayname)) {
            $this->displayname = $this->display_name_from_file($details['file']);
        }

        // Create a course module to hold the new instance.
        $this->create_course_module();

        // Ask the module to set itself up.
        $moduledata = $this->prepare_module_data($draftitemid);
        $instanceid = plugin_callback('mod', $this->module->name, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
        if ($instanceid === 'invalidfunction') {
            throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
        }

        // Finish setting up the course module.
        $this->finish_setup_course_module($instanceid);
    }
185923
def upload(config, remote_loc, u_filename):
    """"""
    rcode = False
    try:
        sftp, transport = get_sftp_conn(config)
        remote_dir = get_remote_path(remote_loc)
        for part in ['sha1', 'asc']:
            local_file = '%s.%s' % (u_filename, part)
            remote_file = os.path.join(remote_dir, local_file)
            sftp.put(local_file, remote_file)
        sftp.put(remote_dir, os.path.join(remote_dir, u_filename))
        rcode = True
    except BaseException:
        pass
    finally:
        if 'transport' in locals():
            transport.close()
    return rcode
574889
def handle(self, pkt, raddress, rport):
        ""
        log.debug("In TftpStateServerRecvWRQ.handle")
        sendoack = self.serverInitial(pkt, raddress, rport)
        path = self.full_path
        if self.context.upload_open:
            f = self.context.upload_open(path, self.context)
            if f is None:
                self.sendError(TftpErrors.AccessViolation)
                raise TftpException("Dynamic path %s not permitted" % path)
            else:
                self.context.fileobj = f
        else:
            log.info("Opening file %s for writing" % path)
            if os.path.exists(path):
                # FIXME: correct behavior?
                log.warning("File %s exists already, overwriting..." % (
                    self.context.file_to_transfer))
            # FIXME: I think we should upload to a temp file and not overwrite
            # the existing file until the file is successfully uploaded.
            self.make_subdirs()
            self.context.fileobj = open(path, "wb")

        # Options negotiation.
        if sendoack:
            log.debug("Sending OACK to client")
            self.sendOACK()
        else:
            log.debug("No requested options, expecting transfer to begin...")
            self.sendACK()
        # Whether we're sending an oack or not, we're expecting a DAT for
        # block 1
        self.context.next_block = 1
        # We may have sent an OACK, but we're expecting a DAT as the response
        # to either the OACK or an ACK, so lets unconditionally use the
        # TftpStateExpectDAT state.
        return TftpStateExpectDAT(self.context)