【SpringMvc实用】file文件上传

文件上传:
文件上传顾名思义就是将文件上传到指定区域进行保存。

上传准备:
在web.xml配置上传文件格式:

<servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
 </servlet-mapping>
 <!--根据自己的需要配置-->

在springmvc的配置文件添加文件上传解析器:

<!--文件上传解析器-->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<property name="maxUploadSize" value="10240000"></property>
	</bean>

适配器,视图解析器等的配置是springmvc必要的,附上配置备用

<!-- 将controller交给spring管理 -->
    <context:component-scan base-package="com.ssm"></context:component-scan>

    <!--
        <mvc:annotation-driven/>默认创建RequestMappingHandlerMapping,RequestMappingHandlerAdapter
        提供对json数据格式支持
    -->
    <mvc:annotation-driven/>

    <!-- 配置视图解析器:解析出真正的物理视图
        后台返回逻辑视图:index
        解析出真正的物理视图,前端+逻辑视图+后缀==/WEB-INF/index.jsp(/index.jsp)
    -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

在spring配置文件中配置路径

<!--配置路径-->
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <mvc:resources mapping="/static/upload/**" location="/static/upload/"/>

这是存放路径:
存放路径


jsp:

<h1>添加视频</h1>
<form action="${pageContext.request.contextPath}/video/insertVideo.do" method="post"  enctype="multipart/form-data" id="videoitem">
    <span>视频名称:</span><input type="text" name="video" id="video"/>&nbsp;&nbsp;
    <span>介绍:</span><input type="text" name="note" id="note">&nbsp;&nbsp;
    <hr/>
    <input type="file" id="upload" name="upload" class="upload">
    <input type="submit" value="添加"/>
</form>

controller:

@RequestMapping("insertVideo")
    public String insertVideo(MultipartFile upload, HttpServletRequest request,String video,String note) throws IOException {

        //使用fileupload组件完成文件上传
        //上传位置指定
        //上传的位置要指定
        String path = request.getSession().getServletContext().getRealPath("/static/upload/");
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            //如果这个文件夹不存在的话,就创建这个文件
            file.mkdirs();
        }
        //获取上传文件名称
        String filename = upload.getOriginalFilename();
        //把文件名称设置成唯一值 uuid 以防止文件名相同覆盖
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //新文件名
        filename = uuid + "_" + filename;
        //完成文件上传
        upload.transferTo(new File(path, filename));
        String NewFilePath = "static/upload/"+filename;

        Video v = new Video();
        v.setVideo(video);
        v.setVsrc(NewFilePath);
        v.setNote(note);
        videoService.insertVideo(v);

        return "redirect:list.do";
    }

运行结果:
在这里插入图片描述在这里插入图片描述在这里插入图片描述

发布了17 篇原创文章 · 获赞 1 · 访问量 629

猜你喜欢

转载自blog.csdn.net/weixin_43316702/article/details/105277249