0 版本是springmvc4
1 首先在springmvc.xml中加入
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
2 表格中 设置enctype 和file
<form role="form" method="post" enctype="multipart/form-data"
action="${pageContext.request.contextPath}/admin/publishActivity.do">
<div class="card-body">
<div class="form-group">
<label for="exampleInputEmail1">活动名字</label>
<input type="text" class="form-control" name="title" placeholder="Enter ...">
</div>
<div class="form-group">
<label>活动内容</label>
<textarea class="form-control" rows="10" name="content" placeholder="Enter ..."></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">活动图片</label>
<div class="input-group">
<div class="custom-file">
<input type="file" class="" size="80" id="exampleInputFile" name="pic"/>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">提交</button>
</div>
</form>
</div>
3 servlet中 参数multipartfile
public ModelAndView publishActivity(Activity activity, @RequestParam MultipartFile pic)throws Exception{
此处可能要加入@RequestParam
4 传入文件
String originalFilename = pic.getOriginalFilename();
if (pic != null && originalFilename != null && originalFilename.length() > 0)
{
String pic_path = "C:\\Pic\\Activity\\";
String newFileName = "活动_" + activity.getTitle()
+ originalFilename.substring(originalFilename.lastIndexOf("."));
File newFile = new File(pic_path + newFileName);
pic.transferTo(newFile);
activity.setPicPath(newFileName);
}
5 这里传入的路径为相对路径,因为如果用绝对路径的话,显示的图片的地址为http://localhost:8080/campus_second_ssh/C:Pic/
这种类型的,不能显示,要现在tomcat中设置路径
在tomcat的安装目录下,conf文件夹下,server.xml中(不要用这种方法,tomcat会把他覆盖掉)
在eclipse下的tomcat 下的server.xml
设置路径
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log" suffix=".txt"/>
<Context docBase="C:\Pic\Buyer" path="/buyer" reloadable="true"/>
<Context docBase="C:\Pic\Seller" path="/seller" reloadable="true"/>
<Context docBase="C:\Pic\Product" path="/product" reloadable="true"/>
<Context docBase="C:\Pic\Activity" path="/activity" reloadable="true"/>
<Context docBase="E:\Tomcat8\upload\temp" path="/pic" reloadable="true"/><Context docBase="campus_second_ssh" path="/campus_second_ssh" reloadable="true" source="org.eclipse.jst.jee.server:campus_second_ssh"/></Host>
在Host内设置context
<Context docBase="C:\Pic\Buyer" path="/buyer" reloadable="true"/>
最后展示为
<img src="/buyer/${buyer.picPath }">