0

I have a webpage that accepts an image via <input type="file" name="imgFile" accept="image/*" />

What I was hoping to accomplish is that when I submit the form, the image is shown on another page, .jsp to be exact, with the help of a servlet.

If I cannot do that exactly (passing an image directly from one jsp to another), how do I do it by writing the file locally on my disk and reading it on my jsp file via <img> tag? The file can be stored anywhere on my disk (e.g. C:\Sample), so it won't really matter where I put it. Thank you!

  • Does this answer your question? [Image Upload and Display in JSP](https://stackoverflow.com/questions/8552776/image-upload-and-display-in-jsp) – Shivam Puri Dec 15 '19 at 15:48
  • @ShivamPuri I think that answers the writing part except for `InputStream is = new FileInputStream(new File("../files/backPetals.jpg"));`. I need the file to be read from `` and that the `byte[] buf = new byte[32 * 1024];` be set to the specific bytes of the uploaded image. Thank you, by the way, for helping! – Viany Manuel Dec 16 '19 at 00:06

1 Answers1

0

Heres a code sample that uploads images from a form. Please modify the action and attributes according to your need.

<form:form modelAttribute="modelClass" action="save" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <form:input type="file" path="productLandscapeImage" class="form-control" name="productLandscapeImage" title="Image" value=""/>
        <form:errors path="productLandscapeImage" cssClass="error-tip" element="div" />
    </div>
</form:form>

The model modelClass must contain the attribute

private MultipartFile productLandscapeImage;

In your controller Class

@RequestMapping(value = { "form/save" }, method = RequestMethod.POST)
public String saveProduct(@Valid @ModelAttribute("modelClass") ModelClass modelClass
        BindingResult bindingResult, Model model, HttpServletRequest httpServletRequest) {

     uploadImages(modelClass, httpServletRequest);

}

private void uploadImages(ModelClass modelClass, HttpServletRequest httpServletRequest) {
    if (modelClass.getProductLandscapeImage() != null
        && !modelClass.getProductLandscapeImage().getOriginalFilename().isEmpty()) {
        String realPath = httpServletRequest.getSession().getServletContext().getRealPath("/resources/images/categories/");
        if (!new File(realPath).exists()) {
            new File(realPath).mkdirs();
        }
        try {
            modelClass.getProductLandscapeImage().transferTo(new File(realPath + ".jpg"));
        } catch (IllegalStateException | IOException e) {
            // log error
        }
    }
}

In Your DispatcherServletInitializer Class add the following method

public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{    
        /**
         * maxFileSize: Maximum Size of the file to be uploaded
         * maxRequestSize: Maximum Size of the multipart/form-data request
         * fileSizeThreshold: Size threshold after which the file will be written to disk
         * 
         * The Size are in bytes
         * 1024  * 1024  *  1 = 1MB
         * 1024  * 1024  *  2 = 2MB
         * 1024  * 1024  *  4 = 4MB
         */
        @Override
        protected void customizeRegistration(Dynamic registration) {
            MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/", 2097152, 8388608, 1048576);
            registration.setMultipartConfig(multipartConfigElement);
        }
}

In Your Web Config Class add the following bean

@Configuration
@ComponentScan(basePackages = {"com.package"})
@EnableWebMvc
public class SpringWebConfiguration implements WebMvcConfigurer{
        @Bean
        public MultipartResolver multipartResolver() {
            return new StandardServletMultipartResolver();
        }
}

Please see this link for full code Full Code Git

Gaming God
  • 29
  • 8
  • Thank you for answering. I'm sorry, but I'm still a novice programmer. I'm still unsure where to write these codes. Should I be creating new classes for each of the classes you've mentioned? Thank you, and I'm sorry again for not understanding you clearly. – Viany Manuel Dec 16 '19 at 00:03