PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label cloudinary. Show all posts
Showing posts with label cloudinary. Show all posts

Sunday, July 31, 2022

[FIXED] How to convert a multipart file to File?

 July 31, 2022     cloudinary, file-upload, java, spring, spring-mvc     No comments   

Issue

Can any one tell me what is a the best way to convert a multipart file (org.springframework.web.multipart.MultipartFile) to File (java.io.File) ?

In my spring mvc web project i'm getting uploaded file as Multipart file.I have to convert it to a File(io) ,there fore I can call this image storing service(Cloudinary).They only take type (File).

I have done so many searches but failed.If anybody knows a good standard way please let me know? Thnx


Solution

You can get the content of a MultipartFile by using the getBytes method and you can write to the file using Files.newOutputStream():

public void write(MultipartFile file, Path dir) {
    Path filepath = Paths.get(dir.toString(), file.getOriginalFilename());

    try (OutputStream os = Files.newOutputStream(filepath)) {
        os.write(file.getBytes());
    }
}

You can also use the transferTo method:

public void multipartFileToFile(
    MultipartFile multipart, 
    Path dir
) throws IOException {
    Path filepath = Paths.get(dir.toString(), multipart.getOriginalFilename());
    multipart.transferTo(filepath);
}


Answered By - Petros Tsialiamanis
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, May 10, 2022

[FIXED] Why can't I apply effects to images in Cloudinary folder?

 May 10, 2022     cloudinary, image     No comments   

Issue

I'm trying out Cloudinary to get optimized images, and as a placeholder I want a blurred image. If the image is in my root media folder, this is no problem, see for instance this url: https://res.cloudinary.com/dvghwblv8/image/upload/e_blur:2000,f_webp/sample.jpg

However, if I want to apply an effect to an image in one of my folders, I get a 404: https://res.cloudinary.com/dvghwblv8/image/upload/q_auto,f_webp,e_blur:1000/samples/landscapes/landscape-panorama

Notice that as soon as I remove my effect, I do get my image: https://res.cloudinary.com/dvghwblv8/image/upload/q_auto,f_webp/samples/landscapes/landscape-panorama

Why can I not apply effects to images that are in a folder?


Solution

Generally, when Cloudinary returns an error for an image/video URL that failed to load due to a problem with the image/video or URL, they will return an HTTP header containing more information about why the request failed.

They also return this header for requests where an image was returned but there was a warning, such as when the default image placeholder was sent instead of the requested image.

This information is sent in the x-cld-error header, and you can see the value by using your browser's web developer tools to examine the request and response for the image which didn't load correctly.

In your current case, the specific error is:

Maximum image size is 25 Megapixels. Requested 25.62 Megapixels

The error is returned as the dimensions of the output image (10,906px by 2,349px - (which are the original image dimensions as no resizing has been requested in your URL) - contains more Megapixels than your account's limit.

You can bypass this error by applying some resizing transformations to your image which will reduce the total number of megapixels of the output. You will not only want to do that to avoid this issue but also because delivering such a large image will result in a large output image in terms of bytes which will then count against your Bandwidth quota in Cloudinary for every request - for instance, the q_auto,f_webp is almost 3MB in size at the original image dimensions.

For example, you can ask Cloudinary to scale the image to 2,000px width (by adding c_scale and w_2000) as follows and then your blurred image will generate and be returned: https://res.cloudinary.com/dvghwblv8/image/upload/c_scale,q_auto,f_webp,e_blur:1000,w_2000/samples/landscapes/landscape-panorama

The above resized version is also only 14.4KB in size and the same w_2000 version and without e_blur it's 115KB - a lot less than the 3MB image when just using q_auto,f_webp and the original (10,906x2,349) dimensions.



Answered By - Aleksandar
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, May 6, 2022

[FIXED] how to upload multiple images to a blog post in django

 May 06, 2022     amazon-s3, cloudinary, django, image, image-uploading     No comments   

Issue

I am trying to allow each user to upload multiple pictures to a single blog post. I have been trying to work out the best way to do this for a few days now. What is the best practice to do this?

From what I have read, I should make a seperate image model from the blog post model and use a foreign key. Is that right? Then there is the matter of how to allow them to upload multiple pictures at the same time. Am I right in assuming I should use something like drop zone?

Any advice on best practices for storing the photos is also welcome. I have looked at Amazon s3 and cloudinary. I want to create something which is scalable.

Any help would be much appreciated!


Solution

You'll just need two models. One for the Post and the other would be for the Images. Your image model would have a foreignkey to the Post model:

from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify

class Post(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=128)
    body = models.CharField(max_length=400)
  
def get_image_filename(instance, filename):
    title = instance.post.title
    slug = slugify(title)
    return "post_images/%s-%s" % (slug, filename)  


class Images(models.Model):
    post = models.ForeignKey(Post, default=None)
    image = models.ImageField(upload_to=get_image_filename,
                              verbose_name='Image')

You need to create a form for each model, but they will be related to each other, as in when the user is filling out the form post he has to complete the image form too for the post to successfully be posted, and we shall do that in the views, but for now your form can look something like this

from django import forms
from .models import Post, Images

class PostForm(forms.ModelForm):
    title = forms.CharField(max_length=128)
    body = forms.CharField(max_length=245, label="Item Description.")
 
    class Meta:
        model = Post
        fields = ('title', 'body', )
 
 
class ImageForm(forms.ModelForm):
    image = forms.ImageField(label='Image')    
    class Meta:
        model = Images
        fields = ('image', )

Now this is the most important part of everything, the views, because this is where uploading multiple images to a single magic happens. For us to be able to upload multiple images at once, we need multiple image fields right? That's where you fall in love with Django formsets. We will need django formsets to make this happen, you can read about formsets in the Django documentation, which I have linked :) But here is how your view should look like:

*Very important the imports

from django.shortcuts import render
from django.forms import modelformset_factory
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponseRedirect
from .forms import ImageForm, PostForm
from .models import Images

@login_required
def post(request):
 
    ImageFormSet = modelformset_factory(Images,
                                        form=ImageForm, extra=3)
    #'extra' means the number of photos that you can upload   ^
    if request.method == 'POST':
    
        postForm = PostForm(request.POST)
        formset = ImageFormSet(request.POST, request.FILES,
                               queryset=Images.objects.none())
    
    
        if postForm.is_valid() and formset.is_valid():
            post_form = postForm.save(commit=False)
            post_form.user = request.user
            post_form.save()
    
            for form in formset.cleaned_data:
                #this helps to not crash if the user   
                #do not upload all the photos
                if form:
                    image = form['image']
                    photo = Images(post=post_form, image=image)
                    photo.save()
            # use django messages framework
            messages.success(request,
                             "Yeeew, check it out on the home page!")
            return HttpResponseRedirect("/")
        else:
            print(postForm.errors, formset.errors)
    else:
        postForm = PostForm()
        formset = ImageFormSet(queryset=Images.objects.none())
    return render(request, 'index.html',
                  {'postForm': postForm, 'formset': formset})

In the view, we are getting both of our forms, and it will check both forms whether they are valid or not. In that way, user has to fill the form AND upload all the images which, in this case, are 3 extra=3. Only then will the post successfully get created.

Your template should look like this then:

<form id="post_form" method="post" action="" enctype="multipart/form-data">
 
    {% csrf_token %}
    {% for hidden in postForm.hidden_fields %}
        {{ hidden }}
    {% endfor %}
 
    {% for field in postForm %}
        {{ field }} <br />
    {% endfor %}
 
    {{ formset.management_form }}
    {% for form in formset %}
        {{ form }}
    {% endfor %}
 
 
    <input type="submit" name="submit" value="Submit" />
</form>


Answered By - qasimalbaqali
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing