SSM 整合之文件上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40369944/article/details/84257709

ssm整合:https://blog.csdn.net/qq_40369944/article/details/84256767

1.在spring.xml添加

    <!--配置MultipartResolver:用于处理表单中的file-->
    <!-- 文件上传配置,这里id的名称固定写法 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>		<!--请求的编码格式-->
        <property name="maxUploadSize" value="102400000"></property>	<!--文件最大大小(字节) 1024*1024*50=50M-->
        <property name="resolveLazily" value="true"/>			<!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="uploadTempDir" value="upload"></property>		<!--指定上传文件的临时文件夹,请在项目中创建好目录。-->
    </bean>

 

2.创建Controller



@Controller
@RequestMapping("/index")
public class indexController {



    @RequestMapping(value = "/fileUploadPage.do", method = RequestMethod.POST)
    @ResponseBody
    public String upload(HttpServletRequest req) throws Exception{
        //上传图片
        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
        MultipartFile file = mreq.getFile("file");
        String fileName = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String name=req.getSession().getServletContext().getRealPath("/")+
                "upload\\"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.'));
        FileOutputStream fos = new FileOutputStream(name);
        fos.write(file.getBytes());
        fos.flush();
        fos.close();
        return "/upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.'));
    }
}

3.创建index.jsp

<form action="/index/fileUploadPage.do" enctype="multipart/form-data" method="post">
    <input type="file" name="file" />
    <input type="submit" value="上传"/>
</form>

4.测试

4.1 运行界面:

4.2 结果:返回图片存放地址

可以在项目发布路径中查看图片

猜你喜欢

转载自blog.csdn.net/qq_40369944/article/details/84257709
今日推荐