- 导入jar包
- 配置文件的视图视图解析器
-
<!-- 配置文件的视图解析器 (id必须写成multipartResolver)--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上传文件的大小 --> <property name="maxUploadSize" value="50000"></property> </bean>
-
- 使用form表单进行文件的上传
-
<%@ 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> <script type="text/javascript" src="static/js/jquery-3.3.1.js"></script> <!-- 显示缩略图的javascript插件 --> <script type="text/javascript" src="static/js/uploadPreview.js"></script> </head> <body> <form action="up/upload" method="post" enctype="multipart/form-data"> 文件名:<input type="text" name="myFileName" /><br /> 文件:<input type="file" name="myFile" id="up_img_a" /><br/> <!-- 用于显示浏览的图片(缩略图) --> <img id="imgShow_a" width="100px" height="100px"> <input type="submit" value="上传" /> </form> <!-- 显示缩略图的javascript代码 --> <script type="text/javascript"> function file_click() { new uploadPreview({ UpBtn : "up_img_a", ImgShow : "imgShow_a" }); } window.onload = file_click; </script> </body> </html>
-
- 编写controller类
-
package com.controller; import java.io.File; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/up") public class UploadController { @RequestMapping("/upload") public String upload(String myFileName,MultipartFile myFile,HttpSession session){ //获取文件保存的地址(文件夹) String realPath = session.getServletContext().getRealPath("upload"); File file=new File(realPath); //判断文件夹是否在(不存在就创建一个) if (!file.exists()) { file.mkdir();//创建文件夹 } String fileName = myFile.getOriginalFilename();//获取文件名 String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());//获取当前时间 //使用一个唯一的编码 uuid拼接也可以(把所有的-都替换为空) String uuid = UUID.randomUUID().toString().replace("-", ""); fileName=date+fileName;//拼接文件名(日期+文件名) try { myFile.transferTo(new File(realPath,fileName));//保存文件(参数一:文件夹,参数二:文件) } catch (Exception e) { e.printStackTrace(); } session.setAttribute("smg", myFileName+"保存成功!"); return "main";//跳转的view } }
-