Upload attachment as required by CommentThread class.

        See CommentThread.upload_attachment for details.
970595
def upload_attachment(self, location, data):
        
        self.validate_attachment_location(location)
        content = data.read() if hasattr(data, 'read') else data
        orig_content = content
        if isinstance(content, bytes):
            content = base64.b64encode(orig_content).decode('ascii')
        else:
            pass  # Should be base64 encoded already
        apath = '%s/%s' % (self.attachment_location, location)
        url = '%s/contents/%s' % (self.base_url, apath)
        result = requests.put(
            url, auth=(self.user, self.token), data=json.dumps({
                'message': 'file attachment %s' % location,
                'content': content}))
        if result.status_code != 201:
            raise ValueError(
                "Can't upload attachment %s due to error %s." % (
                    location, result.reason))
        return '[%s](https://github.com/%s/%s/blob/master/%s)' % (
            location, self.owner, self.realm, apath)
1310876
def attach(self, id, filename, url):
        
        Attachment = self.client.model('ir.attachment')
        return Attachment.add_attachment_from_url(
            filename, url, '%s,%s' % (self.model_name, id)
        )
750946
def upload(self):
        
        if self.upload_method == "setup":
            self.upload_by_setup()
        if self.upload_method == "twine":
            self.upload_by_twine()
        if self.upload_method == "gemfury":
            self.upload_by_gemfury()
399801
public void preparePostUpload(final List<Attachment> attachments) {
        tempParts.clear();
        if (!attachments.isEmpty()) {
            for (Attachment a : attachments) {
                if (a.getError() != null) {
                    errorParts.add(createErrorPart(a));
                } else {
                    publicParts.add(createPart(a));
                }
            }
        }
    }
1230321
def get_upload_form(self):
        """"""
        return self.form_class(self.request.POST, self.request.FILES)
485347
public Attachment uploadAttachment(String contentType, File content)
            throws RedmineException, IOException {
        try (InputStream is = new FileInputStream(content)) {
            return uploadAttachment(content.getName(), contentType, is, content.length());
        }
    }
26188
def action_add(self):
        

        form = self.request.form
        parent = api.get_parent(self.context)
        attachment_file = form.get('AttachmentFile_file', None)
        AttachmentType = form.get('AttachmentType', '')
        AttachmentKeys = form.get('AttachmentKeys', '')
        ReportOption = form.get('ReportOption', 'r')

        # nothing to do if the attachment file is missing
        if attachment_file is None:
            logger.warn("AttachmentView.action_add_attachment: Attachment file is missing")
            return

        # create attachment
        attachment = self.create_attachment(
            parent,
            attachment_file,
            AttachmentType=AttachmentType,
            AttachmentKeys=AttachmentKeys,
            ReportOption=ReportOption)

        # append the new UID to the end of the current order
        self.set_attachments_order(api.get_uid(attachment))

        # handle analysis attachment
        analysis_uid = form.get("Analysis", None)
        if analysis_uid:
            analysis = api.get_object_by_uid(analysis_uid)
            others = analysis.getAttachment()
            attachments = []
            for other in others:
                attachments.append(other.UID())
            attachments.append(attachment.UID())
            analysis.setAttachment(attachments)
            # The metadata for getAttachmentUIDs need to get updated,
            # otherwise the attachments are not displayed
            # https://github.com/senaite/bika.lims/issues/521
            analysis.reindexObject()

        else:
            others = self.context.getAttachment()
            attachments = []
            for other in others:
                attachments.append(other.UID())
            attachments.append(attachment.UID())

            self.context.setAttachment(attachments)

        if self.request['HTTP_REFERER'].endswith('manage_results'):
            self.request.response.redirect('{}/manage_results'.format(
                self.context.absolute_url()))
        else:
            self.request.response.redirect(self.context.absolute_url())
1045362
def set_file_to_upload(self, file_to_upload):
        # type: (str) -> None
        
        if 'url' in self.data:
            del self.data['url']
        self.file_to_upload = file_to_upload
827089
def addAttachment(self, oid, file_path):
        
        if self.hasAttachments == True:
            attachURL = self._url + "/%s/addAttachment" % oid
            params = {'f':'json'}
            parsed = urlparse.urlparse(attachURL)

            files = {'attachment': file_path}
            res = self._post(url=attachURL,
                             param_dict=params,
                             files=files,
                             securityHandler=self._securityHandler,
                             proxy_port=self._proxy_port,
                             proxy_url=self._proxy_url)
            return self._unicode_convert(res)
        else:
            return "Attachments are not supported for this feature service."
821436
def post_attachment(self, bugid, attachment):
        ''''''
        assert type(attachment) is DotDict
        assert 'data' in attachment
        assert 'file_name' in attachment
        assert 'summary' in attachment
        if (not 'content_type' in attachment): attachment.content_type = 'text/plain'
        attachment.ids = bugid
        attachment.data = base64.standard_b64encode(bytearray(attachment.data, 'ascii')).decode('ascii')

        return self._post('bug/{bugid}/attachment'.format(bugid=bugid), json.dumps(attachment))
25940
def create(cls, attachment_public_uuid, custom_headers=None):
        

        if custom_headers is None:
            custom_headers = {}

        request_map = {
            cls.FIELD_ATTACHMENT_PUBLIC_UUID: attachment_public_uuid
        }
        request_map_string = converter.class_to_json(request_map)
        request_map_string = cls._remove_field_for_request(request_map_string)

        api_client = client.ApiClient(cls._get_api_context())
        request_bytes = request_map_string.encode()
        endpoint_url = cls._ENDPOINT_URL_CREATE
        response_raw = api_client.post(endpoint_url, request_bytes,
                                       custom_headers)

        return BunqResponseStr.cast_from_bunq_response(
            cls._process_for_uuid(response_raw)
        )
870877
protected function maybeShiftAttachment() {

		if ( ! in_the_loop() || 'attachment' !== get_post_type() ) {
			return;
		}

		if ( in_array( $this->name, [ 'entry', 'post', 'entry/archive', 'entry/single' ] ) ) {

			remove_filter( 'the_content', 'prepend_attachment' );

		} elseif ( 'embed' === $this->name ) {

			remove_filter( 'the_content',       'prepend_attachment'          );
			remove_filter( 'the_excerpt_embed', 'wp_embed_excerpt_attachment' );
		}
	}
252902
private Observable<Attachment> upload(RxComapiClient client, Attachment a) {
        return client.service().messaging().uploadContent(a.getFolder(), a.getData())
                .map(response -> a.updateWithUploadDetails(response.getResult()))
                .doOnError(t -> log.e("Error uploading attachment. " + t.getLocalizedMessage()))
                .onErrorReturn(a::setError);
    }
71344
def get_attachment_formset_kwargs(self):
        
        kwargs = {
            'prefix': 'attachment',
        }

        if self.request.method in ('POST', 'PUT'):
            kwargs.update({
                'data': self.request.POST,
                'files': self.request.FILES,
            })
        else:
            post = self.get_post()
            attachment_queryset = Attachment.objects.filter(post=post)
            kwargs.update({
                'queryset': attachment_queryset,
            })
        return kwargs
974078
def request_upload_token(self, file):
        
        self.kwargs['name'] = os.path.basename(file.name)
        self.kwargs['size'] = os.fstat(file.fileno()).st_size

        response = self._requester.request(
            'POST',
            self.url,
            _kwargs=combine_kwargs(**self.kwargs)
        )

        return self.upload(response, file)
438787
protected function submitAddFile()
    {
        $this->setSubmitted(null, $this->getParam());
        $this->validateComponent('file');
        $this->addFile();
    }
1182983
@InterfaceAudience.Private
    protected void addAttachment(Attachment attachment, String name) {
        Map<String, Object> attachments = (Map<String, Object>) properties.get("_attachments");
        if (attachments == null) {
            attachments = new HashMap<String, Object>();
        }
        attachments.put(name, attachment);
        properties.put("_attachments", attachments);
        if (attachment != null) {
            attachment.setName(name);
        }
    }