Project

General

Profile

Add Attachment to Issue in a script

Added by James Hardy over 14 years ago

Hi,

First of all, while I do a lot of programming, I don't really know ruby, so please excuse any stupid questions I may ask.

I am attempting to get an external application to create issues automatically. The way I am currently doing this is so get the data into XML and parse this in a ruby script running with the script/runner utility. This works fine.

What I am now trying to do is to add attachments to the issue. The files are accessed via HTTP and I can get these as a temp file on the same machine that redmine is running on easily enough, however what I can't work out how to do is how to import this file into redmine and attached to the issue. Can anyone help?

Cheers


Replies (2)

RE: Add Attachment to Issue in a script - Solution - Added by James Hardy about 14 years ago

Answering my own question in case anyone finds this in a search.

The key issue is that Redmine expects that files will be uploaded and therefore expects they will use rails uploaded temp file container (ActionController::UploadedTempfile)

With a litte googling, I found this post: http://www.spiffystores.com/blog/2008/11/06/how-to-fake-an-uploaded-file/

which enabled me to write the following code snippet:

#Parse URL
attachment_uri=URI.parse(attachment_url)
original_filename=attachment_uri.path[attachment_uri.path.rindex('/')+1..-1]
#Get URL and retrieve data
Net::HTTP.start(attachment_uri.host, attachment_uri.port) do |attHttp|
        req = Net::HTTP::Get.new(attachment_uri.path)
        req.basic_auth url.user, url.password #I need this because it is password protected, not needed if yours isn't
        resp = attHttp.request(req)
        content_type=resp.content_type()

        #Now create the fake uploaded file
        attachment_file = ActionController::UploadedTempfile.new(original_filename)
        attachment_file.binmode
        attachment_file.write(resp.body)
        attachment_file.original_path = original_filename
        attachment_file.content_type = resp.content_type
        attachment_file.rewind

        #Create attachment with the uploaded file and other settings defined earlier
        new_attachment=Attachment.create(
                :container => new_issue,           #Issue object defined earlier 
                :file => attachment_file,
                :description => attachment_desc,
                :author => reporter                #User object defined earlier
        )
end

Hope this helps someone

RE: Add Attachment to Issue in a script - Added by ChihKuo Hu over 3 years ago

Nice post, solved my problem, thanks

    (1-2/2)