spring mvc 实现多文件上传,且同时包含表单信息

上篇虽然可以实现上传多个文件,但是没有实现上传多文件的同时上传表单其他信息 利用MultipartFile实现

upload.jsp 内容

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


File Upload!




 
    modelAttribute="multiFileUploadForm" method="post"
  enctype="multipart/form-data">
 


 

 

  

  

 

 
 

 
 

需要创建po类MultiFileUploadForm.java 代码如下

 public class MultiFileUploadForm {
     private String itemname;
     private String description;
    
    
     public String getItemname()
    {
        return itemname;
    }
    public void setItemname(String itemname)
    {
        this.itemname = itemname;
    }
    public String getDescription()
    {
        return description;
    }
    public void setDescription(String description)
    {
        this.description = description;
    }
    private List multiUploadFiles;
     public List getMultiUploadFiles() {
      return multiUploadFiles;
     }
     public void setMultiUploadFiles(List multiUploadFiles) {
      this.multiUploadFiles = multiUploadFiles;
     }

需要创建的controller类内容为:

@Controller
public class MultiFileUploadController {
 @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
 public String uploadFile(
   @ModelAttribute("multiFileUploadForm") MultiFileUploadForm multiFileUploadForm,
   Model model) {
  List fileNames = new ArrayList();
  List requestFiles = new ArrayList();
  System.out.println(multiFileUploadForm.getItemname());
  System.out.println(multiFileUploadForm.getDescription());
  requestFiles = multiFileUploadForm.getMultiUploadFiles();
  if (null != requestFiles && requestFiles.size() > 0) {
   for (MultipartFile mf : requestFiles) {
    fileNames.add(mf.getOriginalFilename());
    try {
     mf.transferTo(new File("D:/Upload/"
       + mf.getOriginalFilename()));
    } catch (IllegalStateException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   model.addAttribute("files", fileNames);
  }
  for (String file : fileNames) {
   System.out.println(file);
  }
  return "items/success";
 }

你可能感兴趣的:(java学习)