Skip to main content

Spring : File Upload





case  1


<form method="POST" action="uploadFile" enctype="multipart/form-data">
File to upload: <input type="file" name="file"><br /> 
Name: <input type="text" name="name"><br /> <br /> 
<input type="submit" value="Upload"> Press here to upload the file!
</form>


case 2


<form method="POST" action="uploadMultipleFile" enctype="multipart/form-data">
File1 to upload: <input type="file" name="file"><br /> 
Name1: <input type="text" name="name"><br /> <br /> 
File2 to upload: <input type="file" name="file"><br /> 
Name2: <input type="text" name="name"><br /> <br />
<input type="submit" value="Upload"> Press here to upload the file!
</form>

package com.journaldev.spring.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * Handles requests for the application file upload requests
 */
@Controller
public class FileUploadController {

 private static final Logger logger = LoggerFactory
   .getLogger(FileUploadController.class);

 /**
  * Upload single file using 
        Spring Controller
  */
 @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
 public @ResponseBody
 String uploadFileHandler(@RequestParam("name") String name,
   @RequestParam("file") MultipartFile file) {

  if (!file.isEmpty()) {
   try {
    byte[] bytes = file.getBytes();

    // Creating the directory to store file
    String rootPath = System.getProperty("catalina.home");
    File dir = new File(rootPath + File.separator + "tmpFiles");
    if (!dir.exists())
     dir.mkdirs();

    // Create the file on server
    File serverFile = new File(dir.getAbsolutePath()
      + File.separator + name);
    BufferedOutputStream stream = new BufferedOutputStream(
      new FileOutputStream(serverFile));
    stream.write(bytes);
    stream.close();

    logger.info("Server File Location="
      + serverFile.getAbsolutePath());

    return "You successfully uploaded file=" + name;
   } catch (Exception e) {
    return "You failed to upload " + name + " => " + e.getMessage();
   }
  } else {
   return "You failed to upload " + name
     + " because the file was empty.";
  }
 }

 /**
  * Upload multiple file using 
            
            Spring Controller
  */

 @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
 public @ResponseBody
 String uploadMultipleFileHandler(@RequestParam("name") String[] names,
   @RequestParam("file") MultipartFile[] files) {

  if (files.length != names.length)
   return "Mandatory information missing";

  String message = "";
  for (int i = 0; i < files.length; i++) {
   MultipartFile file = files[i];
   String name = names[i];
   try {
    byte[] bytes = file.getBytes();

    // Creating the directory to store file
    String rootPath = System.getProperty("catalina.home");
    File dir = new File(rootPath + File.separator + "tmpFiles");
    if (!dir.exists())
     dir.mkdirs();

    // Create the file on server
    File serverFile = new File(dir.getAbsolutePath()
      + File.separator + name);
    BufferedOutputStream stream = new BufferedOutputStream(
      new FileOutputStream(serverFile));
    stream.write(bytes);
    stream.close();

    logger.info("Server File Location="
      + serverFile.getAbsolutePath());

    message = message + "You successfully uploaded file=" + name
      + "
";
   } catch (Exception e) {
    return "You failed to upload " + name + " => " + e.getMessage();
   }
  }
  return message;
 }
}

Comments

Popular posts from this blog

Microservices Design patterns

What are microservices? Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of services that are Highly maintainable and testable Loosely coupled Independently deployable Organized around business capabilities Owned by a small team The microservice architecture enables the rapid, frequent and reliable delivery of large, complex applications. It also enables an organization to evolve its technology stack. You are developing a server-side enterprise application. It must support a variety of different clients including desktop browsers, mobile browsers and native mobile applications. The application might also expose an API for 3rd parties to consume. It might also integrate with other applications via either web services or a message broker. The application handles requests (HTTP requests and messages) by executing business logic; accessing a database; exchanging messages with other systems; and returni...

GraphQL

What is GraphQL  API Standard invented & open-sourced by Facebook Alternative to  REST API  enables declarative data fetching  exposes single endpoint & responds to queries How it works?  Why Graphql? Improvises performance by reducing the data that is to be transferred over the internet Variety of different frontend frameworks and platforms on client-side Fast development speed & expectation for rapid feature development Why Graphql is better than REST? Flexibility & efficient  No more over /under fetching of data Over fetching : Under fetching: Insightful analytics  Schema serves as contract between client and server CORE CONCEPTS : SDL :SCHEMA DEFINITION LANGUAGE Writing Data with mutations 3 kinds of mutations creating new data updating existing data deleting existing data