【SpringMvc实用】file文件上传
程序员文章站
2022-06-03 09:23:50
...
文件上传:
文件上传顾名思义就是将文件上传到指定区域进行保存。
上传准备:
在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"/>
<span>介绍:</span><input type="text" name="note" id="note">
<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";
}
运行结果:
下一篇: Ubuntu16.04:安装docker
推荐阅读
-
的值怎么初始化?">
javascript - 上传文件的值怎么初始化?
-
【SpringMVC】---- 设置最大文件上传大小后,发送超过最大上传大小后,网页却出现连接被重置【已解决】
-
input标签file类型,选择多个文件进行上传
-
SpringMVC国际化与文件上传(五)
-
php文件上传$_FILES move_uploaded_file详细说明
-
SpringMVC + jquery.uploadify实现上传文件功能
-
SpringMVC上传文件FileUpload使用方法详解
-
SpringMVC文件上传及查看的示例代码
-
SpringMVC上传文件的两种方法
-
WebUploader+SpringMVC实现文件上传功能