SSM 实现文件上传

jar包

配置文件

web.xml

<servlet>  
        <servlet-name>MyDispatcher</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <!-- 设置自己定义的控制器xml文件 -->  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:mvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <!-- Spring MVC配置文件结束 -->  
  
    <!-- 拦截设置 -->  
    <servlet-mapping>  
        <servlet-name>MyDispatcher</servlet-name>  
        <!-- 由SpringMVC拦截所有请求 -->  
        <url-pattern>/</url-pattern>  
    </servlet-mapping> 

spring mvc.xml

 <!-- 上传文件的设置 ,maxUploadSize=-1,表示无穷大。uploadTempDir为上传的临时目录 -->  
        <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="5400000"></property>
<property name="uploadTempDir" value="fileUpload/temp"></property>   
       </bean> 

前台页面fileUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  
<%  
    String path = request.getContextPath();  
    String basePath = request.getScheme() + "://"  
            + request.getServerName() + ":" + request.getServerPort()  
            + path + "/";  
%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<title>上传图片测试</title>  
 <base href="<%=basePath%>">  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
</head>  
<body>  
    <center>  
        <form action="file/upfile"  
            method="post" enctype="multipart/form-data">  
            <input type="file" name="file" />   
            <input type="submit" value="上 传" />  
        </form>  
        <h5>上传结果:</h5>  
        <img alt="暂无图片" src="${file}" />  
    </center>  
</body>  
</html>  

controller 层

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller  
@RequestMapping("/file")  
public class FileController {  
  
    @RequestMapping("/toFile")  
    public String toFileUpload() {  
        return "fileUpload";  
    }  
  
    @RequestMapping("/toFile2")  
    public String toFileUpload2() {  
        return "fileUpload2";  
    }  
  
    /** 
     * 方法一上传文件 
     */  
    @RequestMapping("/upfile")  
    public String oneFileUpload(  
            @RequestParam("file") CommonsMultipartFile file,  
            HttpServletRequest request, ModelMap model) {  
  
        // 获得原始文件名  
        String fileName = file.getOriginalFilename();  
        System.out.println("原始文件名:" + fileName);  
  
        // 新文件名  
        String newFileName = UUID.randomUUID() + fileName;  
  
        // 获得项目的路径  
        ServletContext sc = request.getSession().getServletContext();  
        // 上传位置  
        String path = sc.getRealPath("/img") + "/"; // 设定文件保存的目录  
  
        File f = new File(path);  
        if (!f.exists())  
            f.mkdirs();  
        if (!file.isEmpty()) {  
            try {  
                FileOutputStream fos = new FileOutputStream(path + newFileName);  
                InputStream in = file.getInputStream();  
                int b = 0;  
                while ((b = in.read()) != -1) {  
                    fos.write(b);  
                }  
                fos.close();  
                in.close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
  
        System.out.println("上传图片到:/img/" + newFileName);  
        // 保存文件地址,用于JSP页面回显  
        String url = "/file/"+newFileName;
        model.addAttribute("file", url);  
        return "fileUpload";  
    }     

注意 配置Tomact 中service.xml  在<host></host>中加入

<Context path="/file"   docBase="D:\Program Files\Tomcat7.0\webapps\SSM\img" debug="0" reloadable="true"/>

因为浏览器拒绝直接访问绝对路径


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值