如何在春季上传文件?

时间:2017-05-23 07:19:26

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

我无法在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>

它是我在控制器中的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

5 个答案:

答案 0 :(得分:4)

在你的控制器中你需要指定你期望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相同&#34; uploadedFileName&#34;

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

将其更改为

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

答案 1 :(得分:3)

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

jupyter notebook

您不需要使用弹簧形式进行文件上传,您可以使用纯HTML

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

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

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

您可以按照完整的教程了解如何在Spring Framework Upload File in Spring MVC framework

中上传文件

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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