How to upload file in spring?

与世无争的帅哥 提交于 2021-02-16 14:59:41

问题


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

@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.

 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

回答1:


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

using

consumes = {"multipart/form-data"}

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"

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

change it to

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



回答2:


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

<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

@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




回答3:


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




回答4:


  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

@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";
}



回答5:


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);
    }
}


来源:https://stackoverflow.com/questions/44128195/how-to-upload-file-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!