【问题标题】:How to upload file in spring?spring如何上传文件?
【发布时间】:2017-10-23 00:23:22
【问题描述】:

我无法在 spring 控制器中获取文件名

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

这是我在控制器中的 post 方法

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

提交后得到警告信息。

 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

【问题讨论】:

    标签: java spring spring-mvc servlets spring-web


    【解决方案1】:

    您也可以使用 MutlipartFile 来上传文件,如下所示。

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

    文件上传不需要使用spring form,用纯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>
    

    您需要在您的应用程序配置中配置 MultipartResolver 对象,如下所示

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

    您可以按照完整教程了解如何在 Spring Framework Upload File in Spring MVC framework 中上传文件

    【讨论】:

    • 另外请注意,如果您只是想增加文件限制,今天您可以使用这些属性spring.servlet.multipart.max-file-size=... spring.servlet.multipart.max-request-size=...
    【解决方案2】:

    在您的控制器中,您需要指定您期望的 mutlipart

    使用

    consumes = {"multipart/form-data"}
    

    并使用 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";
    }
    

    同样在您的 html 中,您输入的文件类型名称应与 RequestParam "uploadedFileName" 相同

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

    改成

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

    【讨论】:

    • 感谢重播,但它给出了相同的警告消息 [http-nio-8080-exec-4] WARN org.springframework.web.servlet.PageNotFound - 不支持请求方法 'POST' [http- nio-8080-exec-4] WARN org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - 处理程序执行导致异常:不支持请求方法'POST'
    • 你的请求是什么?
    • 我只要求控制器读取文件内容并保存到数据库中。但我无法将文件放入控制器中。
    • 尝试从您的 html 表单中删除 enctype="multipart/form-data"
    • 它显示 Http 415 并且现在警告是 [http-nio-8080-exec-10] WARN org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - 处理程序执行导致异常:内容类型'application/x-www-form-urlencoded' 不支持
    【解决方案3】:

    我认为您的表单不是由importQuestion 方法处理的,您可以删除method = RequestMethod.POST 以确保它。

    【讨论】:

    • 谢谢,但我这样做是行不通的。它给出了同样的警告。
    【解决方案4】:
    1. 您的型号名称未引用 MultipartFile
    2. 可以在您的映射中进行交叉引用 试试这个:

       <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="" />
      

    并在您的控制器中设置

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-28
        • 2012-06-16
        • 2019-04-15
        • 2021-01-19
        • 1970-01-01
        • 2016-06-21
        • 2017-09-21
        • 2012-10-12
        相关资源
        最近更新 更多