Image upload AngularJs to Rails4 API - angularjs

I have an angularJs app that sends a base64 encoded image (or file) to my rails4 server api that uses paperclip to store attachments. Everything works fine until the content_type_validation paperclip does.
For some reason, paperclip determines the content-type's been spoofed and get the following error message:
[paperclip] Content Type Spoof: Filename 1413325092.jpg (["image/jpeg"]), content type discovered from file command: application/octet-stream; charset=binary. See documentation to allow this combination.
I create the paperclip attachment with the following code:
def self.create_from_base64(base64_string)
decoded_data = Base64.decode64(base64_string)
# create 'file' understandable by Paperclip
data = StringIO.new(decoded_data)
data.class_eval do
attr_accessor :content_type, :original_filename
end
# set file properties
data.content_type = 'application/octet-stream'
data.original_filename = "#{Time.now.to_i}.jpg"
end
I've tried different things but for some reason even when I set data.content_type = 'application/octet-stream', the error is exactly the same, and paperclip it's been spoofed.
Any ideas?
Thanks,
EDIT:
I have the following validation:
validates_attachment_content_type :file, :content_type => [/png\Z/, /jpe?g\Z/, /application\/octet-stream*/]

Related

Scrapy: continue process result from parse function

I am trying to parse page A, download files listed in the page to local disk, replace URL in page A with URL to the files I saved, and finally save page A to local disk.
I tried file pipeline but it just does not work. The URL in page A looks like http:...php?id=1234 so build-in file_path() returns an error. Overriding file_path() just stops pipeline working without any debug output.
So I found this post:
Answer I referred
After I applied I found the parsing function won't change the data I passed in meta. My code is like:
def ParseClientCaseNote(self,response):
# The function is to download all attachments and replace URL inside pointing to local files
TestMeta='this is to test meta argu'
for a in AttachmentList:
yield scrapy.Request(a,callback=self.DownClientCaseNoteAttach,meta={'test':TestMeta})
self.logger.info('ParseClientCaseNote: after call DownClientCaseNoteAttach, testmeta is: ' + TestMeta)
return
def DownClientCaseNoteAttach(self,response):
TestArg=response.meta['test']
self.logger.info('DownClientCaseNoteAttach: test meta')
self.logger.info(TestArg)
TestArg='this is revised from DownClientCaseNoteAttach'
with open(AbsPath,'wb') as f:
f.write(response.body)
return
I got below result in log:
2018-09-29 09:26:13 [debug] INFO: ParseClientCaseNote: after call DownClientCaseNoteAttach, testmeta is: this is to test meta argu
2018-09-29 09:26:17 [debug] INFO: DownClientCaseNoteAttach: test meta
2018-09-29 09:26:17 [debug] INFO: this is to test meta argu
It seems parsing function is deferred. How can I get the result correctly?
Thanks
I used a workaround to address this. In page A I get file name on web and pass the name to own download function change the url pointing to local file with name on web.
In download function I verify the file name from response.headers['Content-Disposition'].decode(response.headers.encoding) to ensure it is the same as I find on page A before save it.

Google Adwords PHP SDK userAgent validation Error(V201406)

An error has occurred: Validation failed for [userAgent] with value
[]: The property userAgent is required and cannot be NULL, the empty
string, or the default [userAgent]
How can I resolve this exception?
Code example:
require_once 'Google/Api/Ads/AdWords/Lib/AdWordsUser.php';
$user = new AdWordsUser();
$user->LogDefaults();
$targetingIdeaService = $user->GetService('TargetingIdeaService', 'v201406');
Google Adwords SDK version 201406 requires you to set userAgent to a non-empty string by which you can identify your API Request and Google Team can identify where from the Request comes if any problem arises. Put any valid name to userAgent in the auth.ini file.

Google App Engine and ttf font not working

I've got a small problem where google app engine is complaining about my ttf file. This is what it says:
Could not guess mimetype for css/fonts/Pacifico.ttf. Using application/octet-stream.
Now I've followed this link and changed my yaml file appropriately (or so I think):
- url: /css/fonts/(.*\.ttf)
static_files: css/fonts/\1
upload: css/fonts/(.*\.ttf)
mime_type: application/x-font-ttf
But when I do this i get the following:
appcfg.py: error: Error parsing C:\Users\Roberto\Desktop\bootstrap\app.yaml: mapping values are not allowed here
in "C:\Users\Roberto\Desktop\bootstrap\app.yaml", line 25, column 17.
2014-01-16 23:22:16 (Process exited with code 2)
Any help in this matter?
I have done a test with glyphicons-halflings-regular.ttf from the Bootstrap project with the same app.yaml handler that you use (save for the indentation change as per the comments) and can verify that it works as expected:
This leads me to believe that you may using an older version of the GAE SDK (I use 1.8.8) or something else is wrong with your installation.
You can try this: appcfg.py uses python's mimetypes module to guess the type from the file extension so in any case, you should be able to solve the issue by adding the application/x-font-ttf mime type to your OS.
You're on Windows so you need to edit your registry and add a application/x-font-ttf key to HKEY_CLASSES_ROOT\MIME\Database\Content Type and add a string value called Extension with the value .ttf under the new key.
Extended procedure for adding the mimetype to Windows
Open the registry editor: Hit Winkey + R and type regedit, hit Enter
Navigate through the registry to the desired location: open HKEY_CLASSES_ROOT, inside it open MIME, inside that open Database and inside that open Content Type. It's like a folder structure.
Right click on Content Type and select New > Key, give it the name application/x-font-ttf.
Right click on the key you just created and select New > String Value. give it the name Extension.
Double click on the value you just created and assign it the Value data .ttf, hit OK.
Exit regedit and you're done!
Final none: I don't think it can be anything to do with the file itself, because the mimetypes module uses only the file extension to work out the MIME type. Unless there is some crazy unprintable character in the filename. You could try using the glyphicons-halflings-regular font I linked to to eliminate this possibility.

Rackspace cloud files return "application/unknown" as mime-type when uploaded with Jclouds

Basically I have this code which uploads javascripts and other content to Rackspace using Jclouds:
SwiftObject obj = cloudFilesClient.newSwiftObject();
obj.getInfo().setName(name);
obj.getInfo().setContentType(contentType);
obj.setPayload(payloadFile);
cloudFilesClient.putObject(container, obj);
I noticed that Chrome complains about scripts being transferred with text/plain and so set out to investigate. curl -I report instead: Content-Type: application/unknown.
I've Googled a lot and tried to find some clues, and I've tried:
not setting content type at all
setting empty string (found some rumour about that somewhere)
setting to application/javascript (correct)
setting to text/javascript (wrong, but common)
obj.getAllHeaders().put("Content-Type", contentType);
When we used to upload with basic HTTP before, this just worked without setting anything manually at all.
Finally finally managed to figure it out by digging in the source code - this works:
FilePayload payload = new FilePayload(uploadableFile.localPath.toFile());
payload.getContentMetadata().setContentType(uploadableFile.contentType);
obj.setPayload(payload);
In case anyone else is looking for this in the future, posting Q&A.

Generate and download file with jboss seam

I need to add an 'export' function to an existing web app using seam. The purpose is to export search results to a csv file. I have no problem generating a csv, but I do not know how the send the csv back to the user.
I do not want to store the csv on the server because that would be waisted storage space. How could I achieve this in jboss seam?
Use the Document Store Servlet provided by Seam.
Almost copying and pasting from the reference doc, declare the servlet in web.xml like this:
<servlet>
<servlet-name>Document Store Servlet</servlet-name>
<servlet-class>org.jboss.seam.document.DocumentStoreServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Document Store Servlet</servlet-name>
<url-pattern>/seam/docstore/*</url-pattern>
</servlet-mapping>
Then create a export.xhtml file with only <s:resource> tag:
<s:resource xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
data="#{myComponent.csvData}"
contentType="application/vnd.ms-excel"
fileName="#{myComponent.csvFileName}"/>
Generate link for downloading the file in your page with <s:download>:
<s:download src="/csv/export.xhtml">
<h:outputText value="Download CSV"/>
<f:param name="param1" value="somevalue"/>
<f:param name="param2" value="someOtherValue"/>
</s:download>
Finally, implement getCsvData() and getCsvFileName() methods in your component:
// could be byte[], File or InputStream
public InputStream getCsvData() {
// generate data to be downloaded
}
public String getCsvFileName() {
return "myfile.csv";
}
Note that <s:download> propagates conversation (unless you set propagation=none). If you propagate the conversation context probably you won't need to pass any parameter. For large data set it may be preferable to not propagate the conversation and pass parameter to select the data in a request scoped component.
There's a couple of ways:
1) Check the Seam docs for info on using Seam-Excel to programmatically generate your file and then write it out using a mime-type set for CSV - this is all detailed in the docs.
However, I could not get this to work in the latest version of Seam, as it requires a response object, which used to be available from the Seam context but now only returns null.
2) Code the CSV file you want as an Excel xhtml template (see the Seam docs and example projects) and simply render this as normal using an tag.
I do this regularly and it works well, bar the restriction that you cannot supply a filename.
HTH.

Resources