zoukankan      html  css  js  c++  java
  • springmvc中的文件上传

    //需要的jar包:
      com.springsource.org.apache.commons.fileupload-1.2.0.jar
      com.springsource.org.apache.commons.io-1.4.0.jar

    import
    java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; @Controller public class Params { public Params() { System.out.println("costructor...."); } @RequestMapping("/upload") public ModelAndView upload(String name, MultipartFile myFile, HttpServletRequest req)//形参名要与参数名相同 throws FileNotFoundException, IOException { System.out.println(name + "::" + myFile); String originName = myFile.getOriginalFilename(); String absPath = req.getServletContext().getRealPath("/uploads"); System.out.println(absPath); String fileName = UUID.randomUUID().toString() + "."+FilenameUtils.getExtension(originName); File file = new File(absPath, fileName); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } IOUtils.copy(myFile.getInputStream(), new FileOutputStream(file)); return null; } }

    //要在ApplicationContext中配置如下

    <bean id="multipartResolver"
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 设置上传文件的最大尺寸为1MB -->
            <property name="maxUploadSize">
                <value>1048576</value>
            </property>
        </bean>

    表单如下

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="utf-8"%>
    <!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 action="/upload.do" method="post" enctype="multipart/form-data">
        姓名:<input type="text" name="name"><br>
        文件:<input type="file" name="myFile" ><br>
        <input type="submit">
    </form>
    </body>
    </html>
  • 相关阅读:
    v-charts 使用markline标线
    覆盖率平台(5)- 生成覆盖率报告
    覆盖率平台(4)- 测程启动
    覆盖率平台(3)- 测程
    覆盖率平台(2)- 服务配置
    vue路由this.route.push跳转页面不刷新
    递归对比json
    ssh远程执行遇到的一些坑
    免密git clone/git pull
    git用远程代码强制覆盖本地代码
  • 原文地址:https://www.cnblogs.com/tabchanj/p/5697442.html
Copyright © 2011-2022 走看看