spring MVC文件上传和下载
2016-02-20 16:36
471 查看
//上传
controller:
@RequestMapping(value = "uploads.do")
public ModelAndView upload(
@RequestParam(value = "add_attach_stcd",required = false) String add_attach_stcd,
@RequestParam(value = "add_attach_tm",required = false) Date add_attach_tm,
@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
//图片路径
String path = request.getSession().getServletContext().getRealPath("upload");
//图片原始名称
String originalFilename = file.getOriginalFilename();
// String fileName = new Date().getTime()+".jpg";
//新的图片名称
String newFileName=UUID.randomUUID()+originalFilename.substring( originalFilename.lastIndexOf("."));
//常见文件类型
String pictureSuffix = ".jpg.jpeg.png.gif.psd.bmp";
String videoSuffix = ".mp4.avi.mpeg.3gp.mov.exe";
String documentSuffix=".word.zip.pdf.excel.ppt.rtf.xlsx.txt.doc.xls.wpd.html.htm";
//文件类型
int fileType = 0;
if (newFileName.lastIndexOf(".") != -1) {
String suffix = newFileName.substring(newFileName.lastIndexOf(".")).toLowerCase();
// 判断是图片还是视频类型
if (pictureSuffix.indexOf(suffix) != -1) {
fileType = 1;
} else if (videoSuffix.indexOf(suffix) != -1) {
fileType = 2;
}else if (documentSuffix.indexOf(suffix) != -1) {
fileType = 3;
}
}
System.out.println("附件类型:"+fileType);
System.out.println("附件路径:"+path);
File targetFile = new File(path, newFileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
String nowtime = dateFormat.format( now );
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date time=null;
try {
time= sdf.parse(sdf.format(new Date()));
} catch (ParseException e1) {
e1.printStackTrace();
}
System.out.println(nowtime);
//文件信息保存到数据库里
StationAttach attach=new StationAttach();
attach.setStcd(add_attach_stcd);
attach.setTm(time);
attach.setAttach_desc(newFileName);
attach.setAttach_url(path);
attach.setAttach_type(fileType);
attachservice.addStationAttach(attach);;
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+newFileName);
return new ModelAndView(new RedirectView("attach.do"),null);
}
jsp:
<form action="uploads.do" method="post" id="add_form" enctype="multipart/form-data">
<table style="border-spacing:15px" id="fileid">
<tr>
<td>测站编码</td>
<td>
<select id="add_attach_stcd" name="add_attach_stcd">
<option value=" " selected="selected">请选择</option>
<c:forEach items="${sessionScope.czbm}" var="item2">
<option value="${item2.stcd}"> ${item2.stcd}</option>
</c:forEach>
</tr>
<tr><td>
添加附件
</td>
<td><input type="file" name="file" ></td>
</tr>
<tr>
<td colspan="3" align="center" >
<div style="float:middle;'">
<div class="btn save_btn" onclick="submit_form('add_form')" style="float:right;'" ></div>
</div>
</td>
<td colspan="3" align="center" >
<div style="float:middle;'">
<div class="btn close_btn" model-close="add" style="float:left;" ></div>
</div>
</td>
</tr>
</table>
</form>
//下载
controller里:
@RequestMapping("download")
public String download( HttpServletRequest request,
HttpServletResponse response) {
String fileName=request.getParameter("fileName");
String path=uploadPath;
//获得第一个点的位置
int index=fileName.indexOf("/");
//根据第一个点的位置 获得第二个点的位置
index=fileName.indexOf("/", index+1);
//根据第二个点的位置,截取 字符串。得到结果 result
String result=fileName.substring(index);
//根据第二个点的位置 获得第三个点的位置
index=fileName.indexOf("/", index+2);
String result2=fileName.substring(index);
String result3=result2.replace("/", "");
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ result3);
try {
InputStream inputStream = new FileInputStream(new File(path
+result));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
jsp页面:
<td>${item.attach_url}<a href="download.do?method=download&fileName=${item.attach_url}">下载</a></td>
数据库:
controller:
@RequestMapping(value = "uploads.do")
public ModelAndView upload(
@RequestParam(value = "add_attach_stcd",required = false) String add_attach_stcd,
@RequestParam(value = "add_attach_tm",required = false) Date add_attach_tm,
@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
//图片路径
String path = request.getSession().getServletContext().getRealPath("upload");
//图片原始名称
String originalFilename = file.getOriginalFilename();
// String fileName = new Date().getTime()+".jpg";
//新的图片名称
String newFileName=UUID.randomUUID()+originalFilename.substring( originalFilename.lastIndexOf("."));
//常见文件类型
String pictureSuffix = ".jpg.jpeg.png.gif.psd.bmp";
String videoSuffix = ".mp4.avi.mpeg.3gp.mov.exe";
String documentSuffix=".word.zip.pdf.excel.ppt.rtf.xlsx.txt.doc.xls.wpd.html.htm";
//文件类型
int fileType = 0;
if (newFileName.lastIndexOf(".") != -1) {
String suffix = newFileName.substring(newFileName.lastIndexOf(".")).toLowerCase();
// 判断是图片还是视频类型
if (pictureSuffix.indexOf(suffix) != -1) {
fileType = 1;
} else if (videoSuffix.indexOf(suffix) != -1) {
fileType = 2;
}else if (documentSuffix.indexOf(suffix) != -1) {
fileType = 3;
}
}
System.out.println("附件类型:"+fileType);
System.out.println("附件路径:"+path);
File targetFile = new File(path, newFileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
String nowtime = dateFormat.format( now );
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date time=null;
try {
time= sdf.parse(sdf.format(new Date()));
} catch (ParseException e1) {
e1.printStackTrace();
}
System.out.println(nowtime);
//文件信息保存到数据库里
StationAttach attach=new StationAttach();
attach.setStcd(add_attach_stcd);
attach.setTm(time);
attach.setAttach_desc(newFileName);
attach.setAttach_url(path);
attach.setAttach_type(fileType);
attachservice.addStationAttach(attach);;
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+newFileName);
return new ModelAndView(new RedirectView("attach.do"),null);
}
jsp:
<form action="uploads.do" method="post" id="add_form" enctype="multipart/form-data">
<table style="border-spacing:15px" id="fileid">
<tr>
<td>测站编码</td>
<td>
<select id="add_attach_stcd" name="add_attach_stcd">
<option value=" " selected="selected">请选择</option>
<c:forEach items="${sessionScope.czbm}" var="item2">
<option value="${item2.stcd}"> ${item2.stcd}</option>
</c:forEach>
</tr>
<tr><td>
添加附件
</td>
<td><input type="file" name="file" ></td>
</tr>
<tr>
<td colspan="3" align="center" >
<div style="float:middle;'">
<div class="btn save_btn" onclick="submit_form('add_form')" style="float:right;'" ></div>
</div>
</td>
<td colspan="3" align="center" >
<div style="float:middle;'">
<div class="btn close_btn" model-close="add" style="float:left;" ></div>
</div>
</td>
</tr>
</table>
</form>
//下载
controller里:
@RequestMapping("download")
public String download( HttpServletRequest request,
HttpServletResponse response) {
String fileName=request.getParameter("fileName");
String path=uploadPath;
//获得第一个点的位置
int index=fileName.indexOf("/");
//根据第一个点的位置 获得第二个点的位置
index=fileName.indexOf("/", index+1);
//根据第二个点的位置,截取 字符串。得到结果 result
String result=fileName.substring(index);
//根据第二个点的位置 获得第三个点的位置
index=fileName.indexOf("/", index+2);
String result2=fileName.substring(index);
String result3=result2.replace("/", "");
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ result3);
try {
InputStream inputStream = new FileInputStream(new File(path
+result));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
jsp页面:
<td>${item.attach_url}<a href="download.do?method=download&fileName=${item.attach_url}">下载</a></td>
数据库:
相关文章推荐
- Java设计模式 工厂模式
- Fragment使用时出现 java.lang.IllegalStateException
- Java编程思想读书笔记 第1章 对象导论
- java文件复制,重命名
- spring mvc时间string转Date问题(一)
- java分布式对象(RMI+部署使用RMI的程序)
- java 测试 solr更新和查询
- 初识 ScheduledThreadPoolExecutor
- Spring MVC 学习笔记 Viewresol和View
- 搭建持续集成单元测试平台(Jenkins+Ant+Java+Junit+SVN)
- 蓝桥杯 历届试题 打印十字图 java详解
- Java 集合系列03之 ArrayList详细介绍(源码解析)和使用示例
- eclipse常用快捷键
- Spark - ERROR Executor: Exception in tjava.lang.OutOfMemoryError: unable to create new native thread
- Mac上如何安装gradle以及eclipse上如何搭建gradle
- Java发送get及post请求工具方法
- Java认证考试实例疑难辨析(11)
- Spring 资源访问剖析和策略模式应用
- 夯实JAVA基本之一——泛型详解(2):高级进阶
- Servlet JNICALL Java_calcServlet_calc