Rails Paperclip nill the image field if user doesn't upload photo - mongoid

I am working on rails 4 ruby 2 project.
I had paperclip for upload files is working. But when the user doesn't upload any photo, paperclip remove the current uploaded photo and nill the field in the db.
How can I ignore the avatar field in case the user does not upload any photo and keep the previous uploaded one?
My model:
has_mongoid_attached_file :avatar,:styles => { :small => "300x300#"}
Thanks a lot...

Rails 4 use strong parameters gem by default: https://github.com/rails/strong_parameters
You can check if the avatar parameter is nil in the controller and don't permit it in this case. Something like this:
def user_params
if params[:avatar]
params.require(:user).permit(:avatar,:name,...)
else
params.require(:user).permit(:name,...)
end
end

Related

Is there any way to get content of the ZenDesk Attachments instead of redirect URL?

I need to get ZenDesk ticket attachment content like encoded format. ZenDesk API provided only the content url. By using that content url I can only able to get the redirect page of that file. But I need to automate a process that file as Base64 encoded format. Thanks in advance.
Note : I tried to migrate ZenDesk to Salesforce via Dell Boomi.
I found a resolution for my problem and I guess it's the same as yours.
In salesforce apex code I got the url response from zendesk and I used subtring method to get URL of attachment.
After that I used Pagereferece to open the URL, see below:
String exampleMyResponse= '<html><body>You are being <a href="https://xxx.zdusercontent.com/attachment/000001/sdlfkashdf98709udfah?token=eyJhbGciOiJkaX46SgYrFzTEpYqUIzpQeNnl5BMBNoRnUOsgQj389Ei7nNcGOcfGYaavlqLL2qaIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..U8oX8QnYBM1lZMb6rhQGRA.NC3Z9kHC9ZE6HhygIHHan6xWYvoPqziVx76CZ6vcNYHBuAjV-LmBclVJYumKWKXA_PDhXX27z977XKYrLJZSc85a6lJTEqd-V2mP7U6O6r0_6E9hO8CWaA1dyxYYWw8kUsgMFUaPr0wCupxm3NbDzT03ZwO6EBJj79x4UZdauiXfEUrSwdl1pPahlQE2VfFo8DprgX9GQHzRFm5lwMrhA3crogo8Ox';
**//You need to authorize your domain "https://xxx.zdusercontent.com"** in remote site
Pagereference pg = new Pagereference(exampleMyResponse.substringAfter('href="'));
**Blob b = pg.getContentAsPDF();**//Here you can use getContent() too for another type of file
//Example to save PDF
Attachment att = new Attachment(Name = 'stvm_4', Body = b, ContentType = 'application/pdf', ParentId='Sobject_Id');
insert att;

How I can change the source of upload images in HTMLflied in Django model field

I am using django-admin as a cms to create content and React to fetch it, I came cross a point where I need to upload a blog image and when I click on the insert/edit filed, the popup model to upload an image field is only accepts a image-url not an image-file from my computer.
1.how I can make it custom to enable me to upload images from my compute?
2. How I can do both; keep url acceptance and from localdrive options
this is my model
class BlogPost(models.Model):
title = models.CharField(max_length=200)
blurb = HTMLField(max_length=150)
hero_image = models.ImageField(null=True, blank=True, upload_to=get_blog_filepath)
published = models.DateTimeField()

Is there a way to add uploaded image into the database and retrieve it for display in another html page?

I am developing a flask web application currently. However, I do not know how I can get the uploaded images from the user into the SQLite database and retrieve it for later use (such as display it on the homepage and other pages).
I am very new to web development so I am not familar with many programming languages yet. I have seen other pages talking about the use of php, may I know if that is really needed? Are there other ways of doing so in flask?
Would appreciate it if someone is able to guide me.
Thank you!
You can base64 encode an image and use a data: url
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
if you simple paste
data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
in your address bar, you will see a small red dot
In an app this looks like this:
# FLASK_APP=mini_app flask run
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
image = db.Column(db.String)
def create_app(config_filename=None, host="localhost"):
app = Flask("demo_app")
app.config.update(SQLALCHEMY_DATABASE_URI="sqlite://")
db.init_app(app)
with app.app_context():
db.create_all()
user = User(name="test", image="iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==")
db.session.add(user)
db.session.commit()
return app
host = "0.0.0.0"
app = create_app(host=host)
#app.route("/image/<string:user_name>")
def show_profile(user_name):
user = User.query.filter(User.name==user_name).one_or_none()
if user:
return f'User: {user.name}<br/>Pic:<img src="data:image/png;base64, {user.image}"/>'
return "Not Found", 404
if __name__ == "__main__":
app.run(host=host)
then go to
http://localhost:5000/image/test

webapp2 post operation not updating datastore

I am developing a web application using google appengine.
I am trying to update an existing entry in the table but my post operation does not seem to be working.
post script:
r = requests.post("http://localhost:8080", data={'type': 'user', 'id':
'11111', 'name': 'test'})
When running the script there are no errors in the console and when prining r.text I can see the updated name but the page on localhost does not show the updated name and the datastore user still has its previous name.
My model for the main page is:
class Page(webapp2.RequestHandler):
def get(self):
...
def post(self):
user = User().get_user(self.request.get('id')) // query user from data store
user.name = self.request.get('name')
user.put()
// update jinja template
self.request.get('id') is a string. You want to use an integer for the id, or build a key (I am assuming you are using ndb):
user = ndb.Key('User', int(self.request.get('id'))).get()

GAE/J - Blobstore - how to determine if file is not uploaded

I am working on web application and using GAE/J blobstore tutorial http://code.google.com/appengine/docs/java/blobstore/overview.html I was able to upload file to blobstore.
My Problem is my "upload file" option is OPTIONAL on form. So user may or maynot choose to upload the file on my form. So since this field is optional, I do not have any upfront form validation for this field, but then when i submit the form "a blank document with 0kb file gets uploaded to blobstore" since i am not able to determine if user has selected any file or not inside servlet.
I tried Apache file upload (ServletFileUpload..etc) but it keeps returning null everytime.
so not sure, how do i determine if user have selected any file to upload inside servlet?
Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
if (blobs != null && blobs.size() > 0) {
BlobKey blobkey = blobs.get("myFile");
blobkeyStr = blobkey.getKeyString();
}
You can test if a blob was uploaded by checking the size of the blob. If the size is zero, you should delete the blob.
BlobstoreService bs = BlobstoreServiceFactory.getBlobstoreService();
BlobKey blobKey = bs.getUploads(req).get("blob").get(0);
final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
long size = blobInfo.getSize();
if(size > 0){
//process blob
}else{
bs.delete(blobKey);
}
In the dev environment if the user submits a form with an empty file upload, the blobkey will be null, but in production it will be non-null and the blob will be empty. So you should check for both scenarios.
FYI it may be more helpful for you to show your code.
Basically, even though your file upload is optional, you still need to send the request from the form submission through the blobstore upload url anyway. If a file was uploaded, your upload handler that gets control from GAE will be able to get a list (map) of all blobs. If no file was uploaded, that list will be empty. From there, you can process the rest of the form submission as you choose.
For the specifics of how to get that list of uploaded blobs, see this section of the documentation, but basically you're going to make this call:
Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
If that map is empty, there were no blobs uploaded.
I'm assuming that you are using a form to submit directly to your upload URL? If so, you might want to add validation code on your form itself. If they've selected the form then do an async request to get an upload url to submit to. If there is no form attached then submit to a different URL that doesn't process the blob.
So for instance, when they submit, if the form is attached, submit to your servlet that generates the upload URL like this:
BlobstoreService service = BlobstoreServiceFactory
.getBlobstoreService();
String url = service
.createUploadUrl("/uploadurl");
return url;

Resources