• SpringMVC文件上传


    Java代码

     1 package com.geostar.gfstack.operationcenter.core.cloud.action;
     2 
     3 import com.geostar.gfstack.operationcenter.common.basecontroller.BaseAction;
     4 import org.apache.commons.io.FileUtils;
     5 import org.springframework.context.annotation.Scope;
     6 import org.springframework.stereotype.Controller;
     7 import org.springframework.web.bind.annotation.RequestMapping;
     8 import org.springframework.web.bind.annotation.RequestParam;
     9 import org.springframework.web.multipart.MultipartFile;
    10 
    11 import javax.servlet.ServletContext;
    12 import javax.servlet.http.HttpServletRequest;
    13 import java.io.File;
    14 import java.io.IOException;
    15 
    16 /**
    17  * Created by Administrator on 2017/6/7.
    18  */
    19 @Controller
    20 @RequestMapping("fileAction")
    21 @Scope("prototype")
    22 public class FileAction extends BaseAction {
    23 
    24     @RequestMapping("upload")
    25     public void upload(
    26             @RequestParam("file") MultipartFile file,
    27             HttpServletRequest request
    28     ) throws IOException {
    29         System.out.println(file);
    30         if(!file.isEmpty()){
    31             ServletContext sc = request.getSession().getServletContext();
    32             String dir = sc.getRealPath("/upload");    //设定文件保存的目录
    33             String filename = file.getOriginalFilename();    //得到上传时的文件名
    34             FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes());
    35             System.out.println("upload over. "+ filename);
    36         }
    37     }
    38 
    39 }

    JSP代码

     1 <%--
     2   Created by IntelliJ IDEA.
     3   User: Administrator
     4   Date: 2017/6/7
     5   Time: 15:58
     6   To change this template use File | Settings | File Templates.
     7 --%>
     8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     9 <html>
    10 <head>
    11     <title>Title</title>
    12 </head>
    13 <body>
    14 <form action="fileAction/upload" method="post" enctype="multipart/form-data">
    15     <input type="file" name="file" id="file">
    16     <input type="submit">
    17 </form>
    18 </body>
    19 </html>
  • 相关阅读:
    第7章例7-12
    第7章例7-11
    第7章例7-9
    第7章例7-8
    第7章例7-7
    第7章例7-6
    第7章例7-5
    第7章例7-4
    第7章例7-3
    第7章例7-2
  • 原文地址:https://www.cnblogs.com/nihaorz/p/6957740.html
Copyright © 2020-2023  润新知