/*
Batch Upload
------------
Author: Alex Boyce (curiosity26@gmail.com)
4508
function () {
    if (arguments.length === 0) {
        return;
    }

    var ret = Object.create({});

    for (var i = 0; i < arguments.length; i++) {
        for (var n in arguments[i]) {
            ret[n] = arguments[i][n];
        }
    }

    return ret;
}
834385
function post($url, $post_data = null, $files = null) {
      $http = $this->getHandle($url);

      if($files) {
        curl_setopt($http, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));

        $counter = 1;

        foreach($files as $file) {
          $post_data['attachment_' . $counter++] = '@' . $file . ';type=application/octet-stream';
        } // foreach
      } // if

      curl_setopt($http, CURLOPT_POST, 1);
      curl_setopt($http, CURLOPT_POSTFIELDS, $post_data);

      return $this->execute($http);
    }
8539
function() {
         //copy to make real Array
         var args = Array.prototype.slice.call( arguments );
         var action = args.shift();
         args = deduceArgs(args);
         var txn = args[1].txn, data = args[0], callback = args[1].callback,
            comment = args[1].comment, override = args[1].override,
            fileinput = args[1].fileinput;
         var commitNow = false;
         // set changedOnly default to true unless action == replace
         var changedOnly = typeof args[1].changedOnly !== 'undefined'
                              ? args[1].changedOnly : action !== 'replace';
         if (!txn) {
             txn = this.data('currentTxn');
             if (!txn) {
                 txn = new Txn(args[1].url || $.db.url);
                 commitNow = true;
             } else if (args[1].url) {
               konsole.assert(txn.url ===  args[1].url);
             }
         }
      try {
         //konsole.log('execute', action, data, callback);
         var requestIds = [];
         if (data) {
            if (action == 'query') {
                if (!data.conditions) {
                    data = { conditions : data };
                }
                //assert data.query;
                var thisid = this.attr('itemid');
                if (thisid) {
                    if (!data.bindvars) {
                        data.bindvars = {}
                    }
                    data.bindvars['this'] =  thisid;
                }
            } else if (!data[_IDkey] && this.attr('itemid')) {
                data[_IDkey] = this.attr('itemid');
            }
            requestIds = [txn.execute(action, data, callback, this.length ? this[0] : null)];
            if (fileinput)
             txn._addFileInput(fileinput, data, requestIds[0]);
         } else {
            konsole.assert(!fileinput);
            requestIds = this.map(function() {
                var obj = bindElement(this, false, undefined, changedOnly);
                if (override) {
                  if (typeof override == 'function')
                    obj = override(obj);
                  else
                    $.extend(obj[0], override);
                }

                var requestid = txn.execute(action, obj, callback, this);
                $(this).find('[data-dbmethod]').each(function() {
                  txn._addFileInput(this, obj, requestid);
                });
                //konsole.log('about to', action, 'obj', obj);
                return requestid;
            }).get();
         }
         if (comment) { //XXX this is all kind of hacky
            comment = comment.replace('$new0', '$new'+requestIds[0]);
            if (txn.txnComment)
                txn.txnComment += ' and ' + comment;
            else
                txn.txnComment = comment;
         }
       } catch (err) {
         // invoke callback if it hasn't already been bound
         // (if we have requestIds then it has)
         var rollbackCB = null;
         if (callback && !requestIds.length) {
           var elem = this;
           rollbackCB = function(response) {
              // note: if callback returns false event bubbling is stopped
              return callback.call(elem, null, response.error);
           };
         }
         this.dbRollback(rollbackCB, err, txn);
         return this;
       }
         if (commitNow)
            txn.commit(null, this);
         return this;
     }
1291289
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException {
    // This follows the Google Cloud Storage guidelines for initiating resumable uploads:
    // https://cloud.google.com/storage/docs/resumable-uploads-xml
    HttpRequestFactory requestFactory =
        httpTransport.createRequestFactory(
            req -> {
              HttpHeaders headers = createHttpHeaders();
              headers.setContentLength(0L);
              headers.set("x-goog-resumable", "start");
              req.setHeaders(headers);
              req.setLoggingEnabled(true);
            });

    try {
      HttpRequest httpRequest =
          requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent());
      HttpResponse response = httpRequest.execute();
      if (response.getHeaders() == null || response.getHeaders().getLocation() == null) {
        throw new BatchJobException(
            "Initiate upload failed. Resumable upload URI was not in the response.");
      }
      return URI.create(response.getHeaders().getLocation());
    } catch (IOException e) {
      throw new BatchJobException("Failed to initiate upload", e);
    }
  }
457062
function (options, testOnly) {
            options.uploadedBytes = options.uploadedBytes || 0;
            var that = this,
                file = options.files[0],
                fs = file.size,
                ub = options.uploadedBytes,
                mcs = options.maxChunkSize || fs,
                slice = this._blobSlice,
                dfd = $.Deferred(),
                promise = dfd.promise(),
                jqXHR,
                upload;
            if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
                options.data) {
                return false;
            }
            if (testOnly) {
                return true;
            }
            if (ub >= fs) {
                file.error = options.i18n('uploadedBytes');
                return this._getXHRPromise(
                    false,
                    options.context,
                    [null, 'error', file.error]
                );
            }
            // The chunk upload method:
            upload = function () {
                // Clone the options object for each chunk upload:
                var o = $.extend({}, options),
                    currentLoaded = o._progress.loaded;
                o.blob = slice.call(
                    file,
                    ub,
                    ub + mcs,
                    file.type
                );
                // Store the current chunk size, as the blob itself
                // will be dereferenced after data processing:
                o.chunkSize = o.blob.size;
                // Expose the chunk bytes position range:
                o.contentRange = 'bytes ' + ub + '-' +
                    (ub + o.chunkSize - 1) + '/' + fs;
                // Process the upload data (the blob and potential form data):
                that._initXHRData(o);
                // Add progress listeners for this chunk upload:
                that._initProgressListener(o);
                jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
                    that._getXHRPromise(false, o.context))
                    .done(function (result, textStatus, jqXHR) {
                        ub = that._getUploadedBytes(jqXHR) ||
                            (ub + o.chunkSize);
                        // Create a progress event if no final progress event
                        // with loaded equaling total has been triggered
                        // for this chunk:
                        if (currentLoaded + o.chunkSize - o._progress.loaded) {
                            that._onProgress($.Event('progress', {
                                lengthComputable: true,
                                loaded: ub - o.uploadedBytes,
                                total: ub - o.uploadedBytes
                            }), o);
                        }
                        options.uploadedBytes = o.uploadedBytes = ub;
                        o.result = result;
                        o.textStatus = textStatus;
                        o.jqXHR = jqXHR;
                        that._trigger('chunkdone', null, o);
                        that._trigger('chunkalways', null, o);
                        if (ub < fs) {
                            // File upload not yet complete,
                            // continue with the next chunk:
                            upload();
                        } else {
                            dfd.resolveWith(
                                o.context,
                                [result, textStatus, jqXHR]
                            );
                        }
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        o.jqXHR = jqXHR;
                        o.textStatus = textStatus;
                        o.errorThrown = errorThrown;
                        that._trigger('chunkfail', null, o);
                        that._trigger('chunkalways', null, o);
                        dfd.rejectWith(
                            o.context,
                            [jqXHR, textStatus, errorThrown]
                        );
                    });
            };
            this._enhancePromise(promise);
            promise.abort = function () {
                return jqXHR.abort();
            };
            upload();
            return promise;
        }
506703
function(options, cb) {
  if (os_name == 'windows') {
    path_arg = path.resolve(options.path);
    name_arg = path.resolve(options.name);
  } else {
    path_arg = '"' + options.path + '"';
    name_arg = '"' + options.name + '"';
  }
  var opts = {
    user: options.user,
    bin: node_bin,
    type: 'exec',
    args: [path.join(__dirname, 'upload.js'), path_arg, options.user, name_arg, options.size, options.file_id, options.total, options.port],
    opts: {
      env: process.env
    }
  };

  run_as_user(opts, function(err, out) {
    if (err) {
      logger.error("Upload error: " + err.message);
      return;
    }
    logger.info("Ran as user: " + out);
    if (out.indexOf("File succesfuly uploaded") != -1) {
      files.del(options.file_id);
      return;
    }
    if (out.includes("EPIPE") || out.includes("EACCES")) {
      files.update(options.file_id, options.path, options.size, options.user, options.name, options.resumable, function(err) {
        if (err) logger.error("Database update error");
        logger.info("Resume file option activated for ID: " + options.file_id);
      });
    }
  });
}
804732
function uploadFileList(files){

		// FileList
		if(!("FileList" in window) || (files instanceof File) || (files instanceof Blob)){
			// Make an Array
			files = [files];
		}


		var max = 20, len = files.length;
		if(len>max){
			var bool = confirm("You man only upload "+max+" files at a time");
			if(!bool){
				return;
			}
			len = max;
		}

		// Loop through the array and place the items on the page
		for(var i=0;i<len;i++){
			createRef(files[i]);
		}
	}
409891
@POST
	@Path("/upload")
	@Consumes("multipart/form-data")
	@AllowSecurityBypassedByToken
	public void upload(MultipartFormDataInput input) throws IOException {
		Map<String, List<InputPart>> formDataMap = input.getFormDataMap();
		List<InputPart> inputParts = formDataMap.get("uploadedFile");

		for (InputPart inputPart : inputParts) {
			String fileName = getFileName(inputPart.getHeaders());
			InputStream inputStream = inputPart.getBody(InputStream.class, null);
			File file = File.createTempFile(HomeWS.class.getSimpleName(), ".tmp");
			IOUtils.copy(inputStream, new FileOutputStream(file));
			uploadedFiles.put(fileName, file);
		}
	}
1139632
private static function upload_prepare(
        $fileSize, $sha1, $sliceSize,
        $sign, $url, $bizAttr = null, $insertOnly = null)
    {
        $data = [
            'op'       => 'upload_slice',
            'filesize' => $fileSize,
            'sha'      => $sha1,
        ];

        if (isset($bizAttr) && strlen($bizAttr)) {
            $data['biz_attr'] = $bizAttr;
        }

        if (isset($insertOnly)) {
            $data['insertOnly'] = (($insertOnly == 0) ? 0 : 1);
        }

        if ($sliceSize <= self::SLICE_SIZE_3M) {
            $data['slice_size'] = $sliceSize;
        } else {
            $data['slice_size'] = self::SLICE_SIZE_3M;
        }

        $req = [
            'url'     => $url,
            'method'  => 'post',
            'timeout' => self::$timeout,
            'data'    => $data,
            'header'  => [
                'Authorization:'.$sign,
            ],
        ];

        $ret = self::sendRequest($req);

        return $ret;
    }
283659
function upload(filesPaths) {
  const promises = filesPaths.map((v, i) => {
    const file = fs.createReadStream(v)
    const formData = {
      projectName: 'FrontEndResource',
      files: [file],
      path: 'frontend',
      usrName: '飞鱼籽',
    };
    return new Promise((resolve, reject) =>
      request.post({
        url: 'http://upload.2dfire-daily.com/upfileandlist',
        formData,
      }, function (error, response, body) {
        if (!error) {
          if (response.statusCode == 200) {
            try {
              const obj = JSON.parse(body)
              resolve({ file: v, response: obj })
              // console.log('success');
            } catch (error) {
              console.error(error);
            }
          } else {
            console.error('upload failed:', response.statusCode);
            reject()
          }
        } else {
          console.error('upload failed:', err);
          reject()
        }
      })
    )
  })

  return Promise.all(promises)
    .then((posts) => posts)
    .catch((e) => { console.error(e) });
}
854693
function upload($args)
    {
        $args['status'] = false;

        $cache = $this->get_cache();
        $key   = $this->_key($args);
        $data  = file_get_contents($args['path']);

        if ($data === false) {
            return $args;
        }

        $data   = base64_encode($data);
        $status = $cache->write($key, $data);

        if ($status) {
            $args['id']     = $key;
            $args['status'] = true;
            $args['path']   = null;
        }

        return $args;
    }
160744
private function _uploadAssetFileFromString($url, $body)
    {
        $blockSize = self::MAX_BLOCK_SIZE;
        $blockIds = [];

        $fileSize = strlen($body);

        if ($fileSize < $blockSize) {
            $this->_uploadAssetFileSingle($url, $body);

            return;
        }

        $totalBytesRemaining = $fileSize;
        $uploadedBytes = 0;

        while ($totalBytesRemaining > 0) {
            $blockContent = substr($body, $uploadedBytes, $blockSize);

            $blockId = $this->_generateBlockId(count($blockIds));

            $blockIds[] = $blockId;
            $this->_uploadBlock($url, $blockId, $blockContent);
            $uploadedBytes += $blockSize;

            $totalBytesRemaining -= $blockSize;
            if ($totalBytesRemaining < $blockSize) {
                $blockSize = $totalBytesRemaining;
            }
        }

        $this->_commitBlocks($url, $blockIds);
    }
696842
function uploadRequest(res, fileObject, showProgress) {
  var url = res.url;
  var expiration = res.expiration;
  var hmac = res.hmac;
  var uuid = res.uuid;
  var file = fileObject.file;
  var uid = fileObject.uid;

  var upload_url = buildUploadURL(url, uuid, expiration, hmac, file.name);

  return new Promise(function (resolve, reject) {
    reqs[uid] = _superagent2.default.put(upload_url).send(file).set({
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }).on('progress', function (e) {
      showProgress(e, fileObject);
    }).end(function (err, res) {
      delete reqs[uid];

      // throw a custom error message
      if (err) return reject(customError('uploadRequest', err));

      resolve(res);
    });
  });
}
540265
function(id, params){
        var file = this._files[id],
            name = this.getName(id),
            size = this.getSize(id);
                
        this._loaded[id] = 0;
                                
        var xhr = this._xhrs[id] = new XMLHttpRequest();
        var self = this;
                                        
        xhr.upload.onprogress = function(e){
            if (e.lengthComputable){
                self._loaded[id] = e.loaded;
                self._options.onProgress(id, name, e.loaded, e.total);
            }
        };

        xhr.onreadystatechange = function(){            
            if (xhr.readyState == 4){
                self._onComplete(id, xhr);                    
            }
        };

        // build query string
        params = params || {};
        params['qqfile'] = name;
        var queryString = qq.obj2url(params, this._options.action);

        xhr.open("POST", queryString, true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.send(file);
    }
81758
function cbk(err, fields, files, resolve) {
    let fileList;

    if (err) {
      debug('upload file error:' + err);
    } else {
      try {
        fileList = createFilenameHash(config.uploadDir, files);
        debug('upload file success！');
      } catch (err) {
        fileList = files;
        debug('create filename hash:' + err);
      }
    }

    resolve(fileList);
  }
1020504
public function doUpload()
    {
        // CJ: Create a folder if it doesn't already exist
        if (!file_exists($this->getOption('location'))) {
            mkdir($this->getOption('location'), 0777, true);
        }

        //use the multup library to perform the upload
        $result = Multup::open('file', 'image|max:'.$this->getOption('size_limit') * 1000, $this->getOption('location'),
                                    $this->getOption('naming') === 'random')
            ->sizes($this->getOption('sizes'))
            ->set_length($this->getOption('length'))
            ->upload();

        return $result[0];
    }
1341491
@POST
  @Path("/upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadFile(
      @FormDataParam("file") InputStream uploadedInputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetail) {

    Config config = createConfig();

    if (uploadedInputStream == null) {
      String msg = "input stream is null";
      LOG.error(msg);
      return Response.status(Response.Status.BAD_REQUEST)
          .type(MediaType.APPLICATION_JSON)
          .entity(Utils.createMessage(msg)).build();
    }
    if (fileDetail == null) {
      String msg = "form data content disposition is null";
      LOG.error(msg);
      return Response.status(Response.Status.BAD_REQUEST)
          .type(MediaType.APPLICATION_JSON)
          .entity(Utils.createMessage(msg)).build();
    }

    String uploadDir = config.getStringValue(FILE_SYSTEM_DIRECTORY);

    final String fileName = UUID.randomUUID() + "-" + fileDetail.getFileName();

    final String uploadedFileLocation
        = uploadDir + "/" + fileName;

    // save it
    try {
      FileHelper.writeToFile(uploadedInputStream, uploadedFileLocation);
    } catch (IOException e) {
      LOG.error("error uploading file {}", fileDetail.getFileName(), e);
      return Response.serverError()
          .type(MediaType.APPLICATION_JSON)
          .entity(Utils.createMessage(e.getMessage()))
          .build();
    }

    String uri = String.format("http://%s:%s/api/v1/file/download/%s",
        getHostNameOrIP(), getPort(), fileName);

    return Response.status(Response.Status.OK).entity(uri).build();
  }