• springMVC文件上传(转)


    原文链接:

    http://www.cnblogs.com/lonecloud/p/5989905.html

    在Spring-mvc.xml注入bean

    复制代码
     1     <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
     2     <bean id="multipartResolver"
     3         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     4         <!-- 默认编码 -->
     5         <property name="defaultEncoding" value="utf-8" />
     6         <!-- 文件大小最大值 -->
     7         <property name="maxUploadSize" value="10485760000" />
     8         <!-- 内存中的最大值 -->
     9         <property name="maxInMemorySize" value="40960" />
    10     </bean>
    复制代码

    如果想要在model里面进行文件上传到数据库中则

    复制代码
     1 package cn.lonecloud.model;
     2 
     3 import java.io.Serializable;
     4 import java.util.List;
     5 
     6 import org.springframework.web.multipart.MultipartFile;
     7 
     8 public class Test implements Serializable{
     9 
    10     private String id;
    11     
    12     private String name;
    13     
    14     private String price;
    15     //文件上传List
    16     private List<MultipartFile> files;
    17 
    18     public String getId() {
    19         return id;
    20     }
    21 
    22     public void setId(String id) {
    23         this.id = id;
    24     }
    25 
    26     public String getName() {
    27         return name;
    28     }
    29 
    30     public void setName(String name) {
    31         this.name = name;
    32     }
    33 
    34     public String getPrice() {
    35         return price;
    36     }
    37 
    38     public void setPrice(String price) {
    39         this.price = price;
    40     }
    41 
    42     public List<MultipartFile> getFiles() {
    43         return files;
    44     }
    45 
    46     public void setFiles(List<MultipartFile> files) {
    47         this.files = files;
    48     }
    49     
    50     
    51 }
    复制代码

    Controller层代码

    复制代码
     1     /**
     2      * 将文件封装在Model里面
     3      * @Description: 
     4      * @param request 用来获取路径
     5      * @param test 封装类
     6      * @param model 返回模型
     7      * @return
     8      */
     9     @RequestMapping("save")
    10     public String saveTest(HttpServletRequest request,
    11             @ModelAttribute Test test, Model model) {
    12         List<MultipartFile> files = test.getFiles();//获取文件
    13         List<String> fileNames = new ArrayList<>();
    14         if (null != files && files.size() != 0) {//判断空
    15             for (MultipartFile multipartFile : files) {
    16                 String fileName = multipartFile.getOriginalFilename();
    17                 String realPath = request.getServletContext().getRealPath(
    18                         "/file");//获取路径
    19                 fileNames.add(fileName);
    20                 File parents = new File(realPath);
    21                 if (!parents.exists()) {
    22                     parents.mkdirs();
    23                 }
    24                 File destFile = new File(parents, fileName);
    25                 try {
    26                     multipartFile.transferTo(destFile);//拷贝文件
    27                 } catch (IllegalStateException e) {
    28                     // TODO Auto-generated catch block
    29                     e.printStackTrace();
    30                 } catch (IOException e) {
    31                     // TODO Auto-generated catch block
    32                     e.printStackTrace();
    33                 }
    34             }
    35         }
    36         model.addAttribute("test", test);
    37         return "fileUpload/details";
    38     }
    复制代码

    直接暴露在控制层当做参数使用

    复制代码
     1     /**
     2      * 直接文件获取
     3      * @Description: 
     4      * @param request
     5      * @param files
     6      * @param result
     7      * @return
     8      */
     9     @RequestMapping("/saveFile")
    10     public String saveFile(@RequestParam("files") List<MultipartFile> files,HttpServletRequest request) {
    11 //        public String saveFile(@RequestParam("files") CommonsMultipartFile[] files,HttpServletRequest request) {
    12         List<String> fileNames = new ArrayList<>();
    13         System.out.println(files);
    14         
    15         if (null != files && files.size() != 0) {
    16 //        if (null != files && files.length != 0) {
    17             for (MultipartFile multipartFile : files) {
    18                 String fileName = multipartFile.getOriginalFilename();
    19                 String realPath = request.getServletContext().getRealPath(
    20                         "/file");
    21                 fileNames.add(fileName);
    22                 File parents = new File(realPath);
    23                 if (!parents.exists()) {
    24                     parents.mkdirs();
    25                 }
    26                 File destFile = new File(parents, fileName);
    27                 try {
    28                     multipartFile.transferTo(destFile);
    29                 } catch (IllegalStateException e) {
    30                     // TODO Auto-generated catch block
    31                     e.printStackTrace();
    32                 } catch (IOException e) {
    33                     // TODO Auto-generated catch block
    34                     e.printStackTrace();
    35                 }
    36             }
    37         }
    38         return "fileUpload/details";
    39     }
    复制代码

     uploadFile.jsp

    复制代码
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <form:form action="save" enctype="multipart/form-data" method="post" commandName="test">
            select a file<input type="file" name="files" multiple><!-- 单文件上传 --><br>
            select files<!-- <input type="file" name="files" multiple> --><!-- 多文件上传 --><br>
            <input type="submit" value="上传">
        </form:form>
    </body>
    </html>
    复制代码
     
     
     
    我的研究:
     @ResponseBody
        @RequestMapping(value = {"/upload_merch_access_file"})
        public Map uploadMerchAccessFile(HttpServletRequest request) {
            Map resultMap = new HashMap<>();
            String filePath = "";
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile("file");
            String fileName = multipartFile.getOriginalFilename();
    
            File targetFile = new File(HUIXIN_BACCESS_FILE + "\" + DateUtil.getDate(), fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            } else {
                resultMap.put("statusCode", 300);
                resultMap.put("message", "已存在同名文件!");
                targetFile.delete();
                targetFile.mkdirs();
                //return resultMap;
            }
            try {
                multipartFile.transferTo(targetFile);
                filePath = targetFile.getPath();
            } catch (Exception e) {
                logger.info("上传批量开通文件异常{}");
                logger.error(e.getMessage());
                resultMap.put("statusCode", 300);
                resultMap.put("message", "上传批量开通文件失败!");
                return resultMap;
            }
            resultMap.put("statusCode", 200);
            resultMap.put("message", "批量开通上传成功!");
            resultMap.put("filename", fileName);
            resultMap.put("filePath", filePath);
            return resultMap;
        }
    这个类:
    MultipartFile

    getName获取的是fileName

    getOriginalFilename获取的是相对路径的Name,切割最后一个到末尾

    transferTo:移动

     这个没看源码。

    
    
  • 相关阅读:
    Ext.FormPanel-----FieldSet的用法
    DAO层,Service层,Controller层、View层
    PageProxy分页的实现
    Layout布局(补充)
    Ext--Layout(布局)
    DirectEvents用法
    Linq的使用
    字符串注入攻击
    winform(C#)里弹出“确定”“取消”对话框
    C#的数组
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/6119168.html
Copyright © 2020-2023  润新知