SpringMVC文件上传

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>


  <!-- 配置Spring 提供的编码过滤器  -->
  <filter>
       <filter-name>EncodingFilter</filter-name>
       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
       <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
       </init-param>
  </filter>
  <filter-mapping>
       <filter-name>EncodingFilter</filter-name>
       <url-pattern>*.do</url-pattern>
  </filter-mapping>
  <!--DispatcherServlet配置-->
  <servlet>
       <servlet-name>SpringMVC</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:applicationContext.xml</param-value>
       </init-param>
  </servlet>
  <servlet-mapping>
       <servlet-name>SpringMVC</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>

Spring配置文件applicationContext.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
xmlns:jee="http://www.springframework.org/schema/jee" 
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<!-- 开启组件扫描  -->
<context:component-scan base-package="com.xdl"  ></context:component-scan>
<!-- 开启标注形式的mvc -->
<mvc:annotation-driven></mvc:annotation-driven>
<!--  配置视图处理器  -->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix"  value="/WEB-INF/"></property>
        <property name="suffix"  value=".jsp"></property>
    </bean>
    <!--  配置一个文件解析器  -->
    <bean  id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- 限定文件大小 -->
         <property name="maxUploadSize" value="1024000"></property>
         <property name="resolveLazily" value="true"></property>
    </bean>

</beans>

文件Md5:

package com.xdl.util;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class Md5Util {
    public static  String  md5Str(String data){
    StringBuffer  strBuf = new StringBuffer();
    try {
MessageDigest   md = MessageDigest.getInstance("MD5");
byte[]  databytes = data.getBytes();
md.update(databytes);
// 获取经过md5 算法处理之后的字节码
byte[]   md5Bytes = md.digest();
System.out.println(md5Bytes.length);
// 如何把 一个 16 长度的byte 数组 变成32 位长度的16进制形式

for(int i=0;i<md5Bytes.length;i++){
byte b = md5Bytes[i];
// 一个byte 等于 8bit  4bit 可以表达成一个位16进制 
// 变成16进制形式时 最长是两位 
String  tempStr = Integer.toHexString(b&0xff); 
//System.out.println(tempStr);
if(tempStr.length() < 2){
tempStr = "0"+tempStr;
}
strBuf.append(tempStr);
}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    return  strBuf.toString();
   
    }  
    /* 加盐 */
    public static  String  md5StrSalt(String data,String salt){
    //"abcd"
    data = data + salt;
    StringBuffer  strBuf = new StringBuffer();
    try {
MessageDigest   md = MessageDigest.getInstance("MD5");
byte[]  databytes = data.getBytes();
md.update(databytes);
// 获取经过md5 算法处理之后的字节码
byte[]   md5Bytes = md.digest();
System.out.println(md5Bytes.length);
// 如何把 一个 16 长度的byte 数组 变成32 位长度的16进制形式

for(int i=0;i<md5Bytes.length;i++){
byte b = md5Bytes[i];
// 一个byte 等于 8bit  4bit 可以表达成一个位16进制 
// 变成16进制形式时 最长是两位 
String  tempStr = Integer.toHexString(b&0xff); 
//System.out.println(tempStr);
if(tempStr.length() < 2){
tempStr = "0"+tempStr;
}
strBuf.append(tempStr);
}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    return  strBuf.toString();
   
    }  

}

文件上传:

package com.xdl.controller;


import java.io.File;
import java.io.IOException;


import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;


import com.xdl.util.Md5Util;


@Controller
public class FileUploadController {
@RequestMapping("/toUpload.do")
    public  String  toUpload(){
    return  "upload";
    }
@RequestMapping("/upload.do")
public  String  upload(MultipartFile  mf,String username,
HttpServletRequest request){
   System.out.println(mf.getOriginalFilename() + ":" + mf.getSize() 
    + ":" +username);
   //获取服务器文件上传的真实路径  然后根据用户id 和 当前系统时间构建一个文件名
   // 保存文件的相对路径 或者 绝对路径 
   String  realPath = request.getServletContext().getRealPath("datas");
   System.out.println(realPath); 
   String oriFileName = mf.getOriginalFilename();
   // 获取后缀
   String  suffix = oriFileName.substring(oriFileName.lastIndexOf("."));
   System.out.println("suffix:"+suffix);
   String fileName = username + "_" + System.currentTimeMillis()
      +"_"+Md5Util.md5Str(mf.getOriginalFilename())+suffix;
   // 构建一个磁盘真实文件 
   File  file = new File(realPath + "/" + fileName);
   try {
    // 把文件转移到磁盘
mf.transferTo(file);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
   // 往request 存放图片的相对路径 
   request.setAttribute("imgPath", "datas/"+fileName);
return  "show";
}
    @ExceptionHandler
    public  String  execute(Exception e){
    return "error";
    } 
}

JSP:

upload.jsp

<%@ 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>
<h3> 文件上传</h3>
<form action="upload.do"  method="post"  enctype="multipart/form-data">
     <input  type="text"  name="username" > <br>
     <input  type="file"  name="mf" > <br>
     <input  type="submit"  value="上传">
</form>
</body>

</html>

show.jsp

<%@ 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>
 <h3>好看吗</h3>
 <img  src="${imgPath}">
</body>

</html>

错误页面:error.jdp

<%@ 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>
    <h3>文件超出限制 最大限制10k</h3>
</body>
</html>

















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值