spring mvc实现图片上传

spring mvc配置文件代码

<!-- 组件扫描 只扫描action -->
    <context:component-scan base-package="com.trace.action" />


    <!-- 使用<mvc:annotation-driven />替换上边定义的处理器映射器和适配器 -->
    <mvc:annotation-driven />

    <!-- 视图解析器 解析jsp视图,默认使用jstl,要求classpath下有jstl的jar包 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 视图的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 视图的后缀 -->
        <property name="suffix" value=".jsp" />

    </bean>
        <!-- 另外最好还要加入DefaultAnnotationHandlerMapping,不然会被 XML或其它的映射覆盖! -->  
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />  


    <!-- 上传功能 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>  

上传Action方法

 @RequestMapping(value = "/upload")  
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {  

        System.out.println("开始");  
        String path = request.getSession().getServletContext().getRealPath("image");  
        String fileName = file.getOriginalFilename();  
        //  String fileName = new Date().getTime()+".jpg";  
        //path:保存路径,fileNmae:文件名称

        System.out.println("保存路劲为"+path);  
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        try {  
            //写入文件
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
            System.out.println("保存失败");
        }  
        //向前台传送数据
        model.addAttribute("fileUrl", request.getContextPath()+"/image/"+fileName);  

        return "result";  
    }  

最终效果
这里写图片描述
上传成功
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值