java How to upload file in spring?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44128195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:57:48  来源:igfitidea点击:

How to upload file in spring?

javaspringspring-mvcservletsspring-web

提问by Anupam Choudhary

I am not able to get the file name in spring controller

I am not able to get the file name in spring controller

<form:form method="post" modelAttribute="sampleDetails" 
 enctype="multipart/form-data">
    <input type="file" name="uploadedFileName" id="fileToUpload" required="" >
    <input type="submit" name="import_file" value="Import File" id="" />
</form:form>

Its my post method in controller

Its my post method in controller

@RequestMapping(method = RequestMethod.POST)
public String importQuestion(@Valid @RequestParam("uploadedFileName") 
MultipartFile multipart, @ModelAttribute("sampleDetails") SampleDocumentPojo sampleDocument,  BindingResult result, ModelMap model) {
    logger.debug("Post method of uploaded Questions ");

    logger.debug("Uploaded file Name : " + multipart.getName());
    return "importQuestion";
}

After submit get the warning message.

After submit get the warning message.

 warning [http-nio-8080-exec-9] WARN 
 org.springframework.web.servlet.PageNotFound - Request method 'POST' not 
 supported
 [http-nio-8080-exec-9] WARN 
 org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver 
 - Handler execution resulted in exception: Request method 'POST' not 
 supported

回答by Amer Qarabsa

in your controller you need to specify that you are expecting mutlipart

in your controller you need to specify that you are expecting mutlipart

using

using

consumes = {"multipart/form-data"}

and to ge the file name using getOriginalFileName()

and to ge the file name using getOriginalFileName()

@RequestMapping(method = RequestMethod.POST, consumes = {"multipart/form-data"})
public String importQuestion(@Valid @RequestParam("uploadedFileName") 
MultipartFile multipart,  BindingResult result, ModelMap model) {
   logger.debug("Post method of uploaded Questions ");

    logger.debug("Uploaded file Name : " + multipart.getOriginalFilename());
   return "importQuestion";
}

Also in your html the name of your input of type file should be the same as the RequestParam "uploadedFileName"

Also in your html the name of your input of type file should be the same as the RequestParam "uploadedFileName"

     <input type="file" name="uploadFileName" id="fileToUpload" required="" >

change it to

change it to

  <input type="file" name="uploadedFileName" id="fileToUpload" required="" >

回答by Ashish Chaudhary

You can also use MutlipartFile in order to upload file as follow.

You can also use MutlipartFile in order to upload file as follow.

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
 @ResponseBody
 public String uploadFile(@RequestParam("file") MultipartFile file) {

 try {

 String uploadDir = "/uploads/";
 String realPath = request.getServletContext().getRealPath(uploadDir);

 File transferFile = new File(realPath + "/" + file.getOriginalFilename()); 
 file.transferTo(transferFile);

 } catch (Exception e) {

 e.printStackTrace();

 return "Failure";
 }

 return "Success";
 }

You don't need to use spring form for file upload, you can do it with plain HTML

You don't need to use spring form for file upload, you can do it with plain HTML

<html>
<body>
 <h2>Spring MVC file upload using Annotation configuration Metadata</h2>

 Upload File :

 <form name="fileUpload" method="POST" action="uploadFile" enctype="multipart/form-data">
 <label>Select File</label> <br />
 <input type="file" name="file" />
 <input type="submit" name="submit" value="Upload" />
 </form>
</body>
</html>

You need to configure MultipartResolver object in yours application configuration as follow

You need to configure MultipartResolver object in yours application configuration as follow

@Bean(name="multipartResolver")
 public CommonsMultipartResolver multipartResolver() {
 CommonsMultipartResolver multi = new CommonsMultipartResolver();
 multi.setMaxUploadSize(100000);

 return multi;
 }

You can follow complete tutorial on how to upload file in Spring Framework Upload File in Spring MVC framework

You can follow complete tutorial on how to upload file in Spring Framework Upload File in Spring MVC framework

回答by leandro lion

  1. your model name not reference to MultipartFile
  2. can have cross reference in yours mappings try this:

     <form:form method="post" action="testcontrol" enctype="multipart/form-data">
    <input type="file" name="uploadedFileName" id="fileToUpload" required="" >
    <input type="submit" name="import_file" value="Import File" id="" />
    

  1. your model name not reference to MultipartFile
  2. can have cross reference in yours mappings try this:

     <form:form method="post" action="testcontrol" enctype="multipart/form-data">
    <input type="file" name="uploadedFileName" id="fileToUpload" required="" >
    <input type="submit" name="import_file" value="Import File" id="" />
    

and set in your controller

and set in your controller

@RequestMapping(method = RequestMethod.POST,path="/testcontrol")
 public String importQuestion(@RequestParam("uploadedFileName") 
MultipartFile multipart,  BindingResult result, ModelMap model) {
    logger.debug("Post method of uploaded Questions ");

    logger.debug("Uploaded file Name : " + multipart.getName());
    return "importQuestion";
}

回答by jagdish belkhade

package com.form.demo.Controll;


import com.form.demo.Repo.CustoRepo;
import com.form.demo.Serv.CustoSevice;
import com.form.demo.model.Customer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Controller
@RequestMapping("/")
public class SimpleWebController {



    private CustoSevice custoSevice;

    public SimpleWebController(CustoSevice custoSevice) {
        this.custoSevice = custoSevice;
    }
    public static String uploadDirectory = System.getProperty("user.dir")+"/uploads";
    @RequestMapping(value={"/","/form"}, method=RequestMethod.GET)
    public String customerForm(Model model) {
        model.addAttribute("customer", new Customer());
        return "form";
    }

    @RequestMapping(value="/form", method=RequestMethod.POST)
    public String customerSubmit(@ModelAttribute Customer customer,Model model,@RequestParam("files") MultipartFile[] files) {
        StringBuilder fileNames = new StringBuilder();
        String path1 = "";
        for (MultipartFile file : files) {
            Path fileNameAndPath = Paths.get(uploadDirectory, file.getOriginalFilename());
            fileNames.append(file.getOriginalFilename()+" ");
            try {
                Files.write(fileNameAndPath, file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            path1=fileNameAndPath.toString();
        }


        customer.setImage(path1);
        model.addAttribute("customer", customer);


        custoSevice.save(customer);

        return "result";
    }

   @RequestMapping(value = "/vewall")
    public String vew(Model model){
        List<Customer>customers=custoSevice.findAll();
        model.addAttribute("cus",customers);
        return "vewall";
   }
    @RequestMapping(value={"/","/update/{id}"}, method=RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") long id, Model model) {
        Customer customer = custoSevice.findById(id);
        model.addAttribute("user", customer);
        return "update";
    }
    @RequestMapping(value={"/","/update/{id}"}, method=RequestMethod.POST)
    public String updateUser(@Valid Customer customer,Model model) {

        custoSevice.save(customer);
        model.addAttribute("cus", custoSevice.findAll());
        return "vewall";
    }
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
    public String deleteUser(@PathVariable("id") long id, Model model) {
        Customer customer = custoSevice.findById(id);

        custoSevice.delete(customer);
        model.addAttribute("cus", custoSevice.findAll());
        return "vewall";
    }


}


package com.form.demo.model;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

@Entity
@Table(name = "cust4")
public class Customer implements Serializable {
    @Id
  //  @GeneratedValue(strategy = GenerationType.AUTO)

    private long id;

    @Column(name = "firstname")

    private String firstname;
    @Column(name = "lastname")

    private String lastname;
    @Column(name = "image")
    private String image;

    public Customer() {
        this.id = id;
        this.firstname = firstname;
        this.lastname = lastname;
        this.image = image;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Customer customer = (Customer) o;
        return id == customer.id &&
                Objects.equals(firstname, customer.firstname) &&
                Objects.equals(lastname, customer.lastname) &&
                Objects.equals(image, customer.image);
    }

    @Override
    public int hashCode() {

        return Objects.hash(id, firstname, lastname, image);
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", firstname='" + firstname + '\'' +
                ", lastname='" + lastname + '\'' +
                ", image='" + image + '\'' +
                '}';
    }
}


<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<meta>
    <meta charset="UTF-8"></meta>
    <title>Title</title>
</head>
<body>
<h1>Customer Form</h1>
<form action="#" th:action="@{/form}" th:object="${customer}" method="post" enctype="multipart/form-data">

    <p>First Name: <input type="text" th:field="*{firstname}" /></p>
    <p>Last Name: <input type="text" th:field="*{lastname}" /></p>
    <p>Image: <input type="file" name="files" multiple></p>
    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    <br>
    <a href="vewall">Viewall</a>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Title</title>
</head>
<body>
<h2>List of cities</h2>

<table>
    <tr>
        <th>ID</th>
        <th>FName</th>
        <th>LName</th>
        <th>Path</th>
        <th>Edit</th>
        <th>Delete</th>
    </tr>

    <tr th:each="city : ${cus}">
        <td th:text="${city.id}">Id</td>
        <td th:text="${city.firstname}">Name</td>
        <td th:text="${city.lastname}">Population</td>
        <td th:text="${city.image}">Path </td>
        <td><a th:href="@{/update/{id}(id=${city.id})}">Edit</a></td>
        <td><a th:href="@{/delete/{id}(id=${city.id})}">Delete</a></td>
    </tr>
</table>
</body>
</html>


spring.datasource.url=jdbc:mysql://localhost:3306/new1
spring.datasource.username=root
spring.datasource.password=root

spring.servlet.multipart.max-file-size=15MB
spring.servlet.multipart.max-request-size=15MB

//
package com.example.demo;

import java.io.File;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import controller.FileUploadController;

@Configuration
@EnableAutoConfiguration
@ComponentScan({"demo","controller"})
public class FileUploadApplication {

    public static void main(String[] args) {
        new File(FileUploadController.uploadDirectory).mkdir();
        SpringApplication.run(FileUploadApplication.class, args);
    }
}

回答by dabaicai

I think you form is not handled by the method importQuestion,you can remove method = RequestMethod.POSTto make sure it.

I think you form is not handled by the method importQuestion,you can remove method = RequestMethod.POSTto make sure it.