其实 上传照片跟上传pdf 还有其他 影音类的文件差不多 就是jsp 页面上显示的方式不一样
废话不多说,直接上代码
1. 上传文件 首先有个上传文件的按钮
其 代码为:
<label class="control-label">上传pdf文件:</label>
<div class="controls">
<input style="width:200px" class="g-file" type="file" name="pictureFile" accept=".pdf" name="file" size="chars" value="请上传"/>
<span class="help-inline"><font color="red"></font> </span>
</div>
</div>
2.设置form表单
- <form:form id="inputForm" modelAttribute="article" action="${ctx}/cms/article/save"
method="post" enctype="multipart/form-data" class="form-horizontal">
3.实体类 两个必要的属性 ①接受文件 ②保存文件名(相当于文件的地址)
数据库中只需要 一个字段保存路径即可
4.controller 层
-
@RequestMapping(value = "save")
public String save(Article article, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
try {
//判断文件是否为空
if (!article.getPictureFile().isEmpty()) {
try {
//1. 获取完整名称
String fileStr = article.getPictureFile().getOriginalFilename();
//2. 使用随机生成的字符串+源图片扩展名组成新的图片名称,防止图片重名
String newfileName = IdGen.uuid().toString() + fileStr.substring(fileStr.lastIndexOf("."));
// 保存的文件路径(如果用的是Tomcat服务器,文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中 )
String filePath = request.getSession().getServletContext().getRealPath("/")
+ "issueimage/" +newfileName;
System.err.println(filePath);
File saveDir = new File(filePath);
if (!saveDir.getParentFile().exists())
saveDir.getParentFile().mkdirs();
System.err.println(filePath);
article.getPictureFile().transferTo(saveDir);
// article.setArchiveAddress(newfileName);
String archive_address=newfileName; //地址路径
if(article.getId()==null||article.getId().equals("")) {
article.setId(IdGen.uuid());
article.setIsNewRecord(true);
article.setCreatePeo(UserUtils.getUser().getId());
article.setAddress(archive_address);
addMessage(redirectAttributes, "新增文章成功!");
}else {
article.setIsNewRecord(false);
addMessage(redirectAttributes, "修改文章成功!");
}
5.jsp 显示方式
照片显示 :