flask file download method not allowed error - file

flask code
#app.route('/usecase/get/excel/<heads>', methods=['GET', 'POST'])
def get_excel(heads):
headers = {"Content-Disposition": "attachment; filename=%s" % "usecase.xls"}
with open("usecase.xls", 'r') as f:
body = f.read()
return Response(response=(body, headers))
html code
<form action="/template/usecase/get/excel/" method="post">
<button type="submit" class="btn btn-info">download</button>
</form>
if click download button, error occured "Method not allowed"..
and how to download server's file? this is exactly program?

Are you matching the right route?
/template/ does not seem to be part of your routing rules unless its some root prefix. Secondly the heads attribute is not optional so you will not hit that route anyway with that request.
On a more picky note: Why are you using a POST request to fetch the data when you clearly imply that you support the GET version.

Related

Cannot display image from backend express react

I'm having a backend server with an upload folder directly in the root.
In my backend, http://localhost:4000, I have my upload folder and I'd like to display the image that matched the url given for each element I have in my backend :
const url = "http://localhost:4000/"
{filteredDrawings && filteredDrawings.map((drawing) => (
etc...
<div className='cardimage-container'>
<Card.Img variant='top' src={`${url}/${drawing.imageLink}`} />
</div>
When checking my browner, i have src="upload/testupload.jpg" displayed as src of the image but I have nothing displayed
I wrote app.use("/upload", express.static(path.join(__dirname, "../upload"))); in my my backend app.
When I try http://localhost:4000/upload/uploadtest.jpg, I have "Cannot GET /upload/uploadtest.jpg"
Thanks in advance
Ok problem solved, the issue was the quote not being ' but `
app.use(`/upload`, express.static(`upload`));
the error you faced is because the route /upload/uploadtest.jpg is not defined well as a route in the nodejs , you should read the document based on id or other identifier and return as a binary.
as for react try {{ }} without $
in this case it should be worked without any problem

Python ValueError: I/O operation on closed file, files saves with no data

I have a form like this:
<form action="/test-upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" />
<input type="submit" name="submit" value="Start upload" />
</form>
And I have a function like this:
#route("/test-upload")
#post("/test-upload")
def test_upload():
if request.POST.get("submit"):
f = request.POST.get("upload")
upload_path = "uploaded_files/{0}".format(f.filename)
f.save(upload_path, overwrite=True)
return "ok"
return template("test_upload")
Which results in the following error:
File "/usr/lib/python3.4/site-packages/bottle.py", line 2389, in save
self._copy_file(fp, chunk_size)
File "/usr/lib/python3.4/site-packages/bottle.py", line 2367, in _copy_file
read, write, offset = self.file.read, fp.write, self.file.tell()
ValueError: I/O operation on closed file
If I change to this, I get the same error as above:
f.save("uploaded_files", overwrite=True)
If I use either of these:
with open(upload_path, 'w') as open_file:
open_file.write(f.file.read())
or
with open(upload_path, 'wb') as open_file:
open_file.write(f.file.read())
I this error:
open_file.write(f.file.read())
ValueError: read of closed file
What's confusing is that something does save to the file system, with the proper extension (I've tested jpeg and pdf), there is no data in any of the files. I just don't see what, if anything, I am doing wrong with either version. I'm looking to upload a file with data.
I'm using Python3.4 with bottle.
some things I've looked at: How to upload and save a file using bottle framework
and: http://bottlepy.org/docs/dev/tutorial.html#file-uploads
try
f = request.files.get('upload') # .files, not .post
f.save(upload_path)
Edit:
#567 In python 3.4 multipart file upload breaks due to change in cgi.FieldStorage
but it should be fixed.
can you try updating your bottle version to the last one?

Image upload AngularJs to Rails4 API

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*/]

For <input type="file" ...> self.request.POST[name] is just a string

Using the GAE "helloworld" example app as a base, but changing "helloworld.py" to:
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.write(
"""
<form method="post">
UPLOAD: <input type="file" name="file_param"/>
<br/>
<input type="submit" name="submit_param" value="Submit">
</form>
"""
)
def post(self):
field_storage = self.request.POST["file_param"]
try:
mimetype = field_storage.type
self.response.write("Mimetype: {}".format(mimetype))
except:
self.response.write("No FieldStorage object, field_storage={}".format(field_storage))
app = webapp2.WSGIApplication([('/', MainPage)], debug=True)
Running this in Google Chrome on Mac OSX:
Click "Choose File"
Choose a file to upload
Click "Submit"
The page that comes back says:
No FieldStorage object, field_storage=<the name of the file I uploaded>
According to http://webapp-improved.appspot.com/guide/request.html#files and examples in various posts, self.request.POST[name] should be a cgi.FieldStorage object. But as this example shows, self.request.POST[name] is a string containing the filename of the uploaded file. If it were a cgi.FieldStorage object, I would expect the program to display the mimetype of the uploaded file.
I need the cgi.FieldStorage object so I can get the mimetype and of course the value, that is, the content of the file. What am I doing wrong?
By the way, switching from webapp2 to webapp (using from google.appengine.ext import webapp) made no difference. Also, running it in Safari or Firefox, it behaved the same as in Chrome.
The form's enctype must be multipart/form-data. Please add it as follows (method attribute is case-insensitive):
<form method="POST" enctype="multipart/form-data">
Also, please consider using blobstore upload, because it doesn't have size limit, you can also use Google Cloud Storage as a backend, which will give you more flexibility on ACL and sharing capability.

Grails AppEngine file upload using GAEVFS

I'm working on Grails web application and need to upload files.
I have a form (simplified here):
<g:form action="save" method="post" enctype="multipart/form-data">
<input type="file" id="image" name="image" />
<input class="save" type="submit" value="Create" />
</g:form>
and in Controller code (I know that this should not be in controller but this is just to make it work and than will be designed better):
def save = {
GaeVFS.setRootPath( servletContext.getRealPath( "/" ) );
FileSystemManager fsManager = GaeVFS.getManager();
FileObject tmpFolder = fsManager.resolveFile( "gae://WEB-INF/upload_files" );
if ( !tmpFolder.exists() ) {
tmpFolder.createFolder();
}
//I NEED CODE HERE TO SAVE THE IMAGE IN THE BIGTABLE VIA GAEVFS
}
So I have two problems:
A. When save create button is pressed a get exception since it tries to use Apache Commons FileUpload that tries to save to file system.
How do I disable it?
Exception is:
java.lang.NoClassDefFoundError: java.rmi.server.UID is a restricted class. Please see the Google App Engine developer's guide for more details.
at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:51)
at org.apache.commons.fileupload.disk.DiskFileItem.(DiskFileItem.java:103)
at org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:196)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:358)
B. I need the code example to save image via gaevfs
I have seen example in GaeVfsServlet but I still don't know how exactly it should look in my case. Any kind of help is welcome.
GaeVfsServlet url: http://code.google.com/p/gaevfs/source/browse/trunk/src/com/newatlanta/appengine/servlet/GaeVfsServlet.java
I came across the very same problem and I am using a grails plugin called ajaxuploader to get around the issue - the file that gets uploaded is available to your controller as an inputstream object and doesnt have to use the commons file upload API at all.
http://www.grails.org/plugin/ajax-uploader

Resources