I have one HTML file, where I am using one image upload button. Now this image is stored in the MySql database as Blob. I need to get or read this image data somehow in Django through post method. Can anyone please help how to do?
Icon is defined like :
icon = models.BinaryField(null=True)
My Html:
<input type="file" id="toolicon" accept="image/*" data-type='image' >
<button id="OpenImgUpload" style="margin-left: 100px">Image Upload</button>
In JQuery:
$('#OpenImgUpload').click(function(){ $('#toolicon').trigger('click'); });
Image:
Now I want to get this file as Binary Field data. Till now I have used :
tool_icon = request.POST('toolicon', '')
tool_icon = request.POST.get('toolicon', '')
tool_icon = base64.b64encode('toolicon', '')
Nothing works ... Can any one please help me.
Uploaded files are contained in request.FILES with the key corresponding to the name attribute on the input element.
So you should add a name attribute to your input:
<input type="file" name="toolicon" ...
And then access the data using request.FILES:
tool_icon = request.FILES.get('toolicon', '')
The request must have a content type of multipart/form-data which you should set on your form:
<form enctype="multipart/form-data" ...
Related
I am fairly new to the Django and HTML world and and would like to be able to select a video file and then play it in an edited version (AI classification and some OpenCV editing).
At the moment, playing of a local file works in that way that the file path of my dummy video file is fixed in my script where I load the VideoStream.
However, I would like to be able to specify via HTML input which file to load.
I have the problem that I do not know how to pass the selected file.
Via urls, parameters can be passed, but I do not know how I can pass the path or URL of the video file as a parameter. Or can something like this be achieved via post requests and if so how?
Here are parts of my script (I don't use post request for this at the moment):
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input id="myFileInput" type="text">
<input class="button1" id="inputfield" name="upload" type="file" accept="video/*" onchange="document.getElementById('myFileInput').src = window.URL.createObjectURL(this.files[0]); document.getElementById('buttonStart').className = 'button'; this.form.submit()" value="Select a File"/>
</form>
The file path is stored in 'myFileInput'. But I could also get the file path through post request. Then I have the problem, that no class instance that I know where I could save that path and load it later.
<img id="demo" src="">
and the function for
function video_on() {
document.getElementById("demo").src = "{% url 'mask_feed' urlpath='path_I_would_like_to_pass' %}"; //
document.getElementById("wait").innerHTML = "Turning on. . . . .";
setTimeout(showText, 3000);
}
and the urls.py file:
path('mask_feed/<path:urlpath>', views.mask_feed, name='mask_feed'),
And of course I have a mask_feed method in my views.py that takes urlpath as argument.
How can I "insert" the file path I get with html insert into the Django template "{% url 'mask_feed' urlpath='path_I_would_like_to_pass' %}"?
I would like to do something like this:
document.getElementById("demo").src = "{% url 'mask_feed' urlpath='document.getElementById('myFileInput').src' %}"
But it doesn't work because of the quotation marks.
And if this is not the way to go, how should I do it?
In Coldfusion, using cffile upload, when a file is selected with the browse button the name of the selected file shows next to the button. So far, so good. When I submit the file for upload, the text changes back to "no file selected". This is doubtless because we are submitting a form.
However, I'm submitting the form to the same page, and would like to see the name of the file selected instead of "no file selected" which is likely to confuse the user.
The code:
<form
enctype="multipart/form-data"
method ="post"
name ="attupload"
action ="">
<cfoutput>
<table style = "margin-left: 40%">
<tr><td>
<input name="theupload"
type="file"
style = "font-family: comic sans ms;
color: ##679C9C">
</td></tr>
</table>
<div style = "width:20%; margin:5% auto 5% 45%">
<input name = "submit"
type = "submit"
class = "submitbut"
style = "font-size: 16px"
value = "Upload File">
</div>
</cfoutput>
</form>
The words 'no file selected' seem to be part of the input name = 'upload' field, but ColdFusion evidently takes control of it, and I cannot insert anything else.
Does anyone know how I can control the 'no file selected' note, so that I can put the name of the selected file back in that spot? I have tried with javascript, but it is simply ignored.
Once a file has been selected, you can access its properties via JavaScript with the File API. You can't affect the value displayed next to the default <input type="file"> field with JavaScript.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file
You should also avoid submitting forms to the same page. You should follow the process:
Form page
HTTP POST to form processing page.
after form processing, <cflocation> (301 redirect) back to a list page or the form page.
When you post to the same page, the user can hit reload and be prompted to resubmit form data. This can be problematic in many situations. As an alternate, you can post the form data using Ajax or better, via Fetch. This avoids a re-post on page reload and redirecting away from the current screen.
Also, you should avoid naming an <input type="submit"> "submit". It can conflict with the JavaScript function submit() should you need to use it.
<input name = "submit"
type = "submit"
class = "submitbut"
style = "font-size: 16px"
value = "Upload File">
I was following LPTHW ex51 by Zed shaw http://learnpythonthehardway.org/book/ex51.html, and was doing his study drills on web.py , i am a web.py beginner and was successful in uploading an image on Webpage form and then storing it in a local folder. The issue is each image I store , replaces the earlier one. Also I cant figure out how to upload multiple images on server and store them all.
Here is my class Upload in app.py:
class Upload(object):
def GET(self):
web.header("Content-Type","text/html; charset=utf-8")
return render.upload()
def POST(self):
x= web.input(myfile={})
filedir= "C:/Users/tejas/Documents/filesave"
if 'myfile' in x:
fout = open(filedir + '/' + 'myfile.jpg', 'wb') # creates the file where the uploaded file should be stored
fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
fout.close() # closes the file, upload complete
return "Success! Your image has been saved in the given folder."
raise web.seeother('/upload')
and my upload form- upload.html :
<html>
<head><title>
<div id="header" <h1 style="color:blue;">Upload image file</h1><div/>
</title></head>
<body background-color=light-blue,font-family=verdana,font-size=100%;>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile"/>
<br/> <br/><br/>
<input type="submit"/>
</form>
</body>
</html>
I tried searching a lot for similar questions but all in PHP , and so I try something similar with the code but I could not get it working. Any suggestions to improve the code?
the reason your code is replacing the earlier on is because your hardcoding the path to save the image
fout = open(filedir + '/' + 'myfile.jpg', 'wb')
everytime you upload the file to be altered is the same this could be corrected by adding an new name each time your uploading new file or extracting the name from web input
fout = open(filedir + '/' + x.myfile.filename, 'wb');
according to python when opening for writing files with the same name will be erased
make sure each new file you upload has different name from the previous uploaded
I have a form that has the following header:
<form enctype="multipart/form-data" target="invisible" action="/calendar/createEvent/" method="POST">
and the follow body:
<input class="multiFileInput" type="file" name="files" onchange="newInput();">
<input class="multiFileInput" type="file" name="files" onchange="newInput()">
<input class="multiFileInput" type="file" name="files" onchange="newInput()">
Along with a lot of other inputs but the file upload are the important one.
This form gets submitted to my view and does everything correctly except for the file uploading.
When I, in the view, execute "print request.FILES" i get:
<MultiValueDict: {u'files': [<TemporaryUploadedFile: boson.mp3 (audio/mpeg)>, <TemporaryUploadedFile: hadron.mp3 (audio/mpeg)>]}>
But when I try to do more with those it won't let me use them as files.
For example, say I have the following tables:
class File(models.Model):
file = models.FileField(upload_to='files')
class Test(models.Model):
name = models.CharField(max_length=10)
files = models.ManyToManyField(File, related_name='files')
If in my view i say:
for f in request.FILES['files']:
test = Test()
test.name='test'
test.save
empt = File()
empt.file = f
empt.save()
test.files.add(empt)
I get the the follow exception:
DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte. You passed in '\xff\xfb\xe0d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Info\x00\x00\x00\x0f\x00\x00\x98C\x02m~\t\x00\x03\x05\x08\n'
Also, if I try to write to a destination say using f.chunks(), I get
AttributeError: 'str' object has no attribute 'chunks'
Any sort of help would be greatly appreciated. I've been stuck on this for a while and would love some help
You should access multipart values with getlist, i.e.:
for afile in request.FILES.getlist('files'):
File(file=afile, files=test).save()
I don't think it's getting the list as a python list when you use request.FILES['files'].
Also, if you want to use the HTML5 multiple file upload instead of many file forms, take a look here: django form with multiple file fields
I haven't done this exact thing before, but it seems like you'd need to do some processing on the actual audio file before saving it.
The general structure would be:
if form.is_valid():
object = form.save(commit=False)
t = handle_uploaded_file(request.FILES['file'])
object.field.save(t[0], t[1])
And in the handle_uploaded_file, you'd probably need to use something like ffmpeg to process the audio and then return (filename, content) to your main function.
In addition, using .chunks would be on the actual file passed:
str=""
for c in request.FILES['file'].chunks():
str += c
In addition to handling the file-array in the request-object correctly as pointed out in the other posts, you should also make sure that in the html input, you have a "multiple"-attribute that is set to true.
Example:
<input name="file_field" multiple="true" required="false" id="id_file_field" data-enpass.usermodified="yes" type="file">
I'm new to coldfusion.
I have page called test1.cfm
<form action = "test2.cfm" method = "post">
Type your name and hit submit:<br>
<input type = "Text" name = "txt1">
<input type = "Submit" name = "" value = "submit">
</form>
And test2.cfm
<cfoutput>
success
#form.txt1#
back
</cfoutput>
Now I want to know if we can encode the displaying of text value in test2.cfm page.
For eg. if we type <br> in the textbox, test2 page will render it as html, and I want to stop rending and it should display as text.
Thanks
It's HTMLEditFormat(), not code.
Use
#htmlCodeFormat(form.txt1)#