您的位置:首页 > 编程语言 > Java开发

spring MVC文件的上传和下载

2015-03-27 08:40 393 查看
/** 文件上传
* @author:zzq
* @createTime:2015-3-23
*/
@RequestMapping(value="/upload.html")
public String upload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
String bookName = null;
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
if(multipartResolver.isMultipart(request)){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator<String> iterator = multipartRequest.getFileNames();//
while(iterator.hasNext()){
MultipartFile file = multipartRequest.getFile((String)iterator.next());
if(file != null){
bookName = file.getOriginalFilename();
String path = request.getSession().getServletContext().getRealPath("/upload/"+bookName);
File localFile = new File(path);
if (!localFile.exists()) {
localFile.mkdirs();
}
file.transferTo(localFile);
}
}
}

//入库
EntrustBook book = new EntrustBook();
book.setBookName(bookName);
entrustBookService.save(book);

return "/contracts/upload_ok";
}

/**
* 文件下载
* @author:zzq
* @createTime:2015-3-24
* @param fileName
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/download.html")
public String download(Integer id,HttpServletRequest request, HttpServletResponse response)throws Exception {
request.setCharacterEncoding("UTF-8");
EntrustBook book = entrustBookService.find(id);
BufferedInputStream bis = null;  //从文件中读取内容
BufferedOutputStream bos = null; //向文件中写入内容

//获得服务器上存放下载资源的地址
String ctxPath = request.getSession().getServletContext().getRealPath("/upload/");
//获得下载文件全路径
String fileName = book.getBookName();
String downLoadPath = ctxPath +"/"+ fileName;
System.out.println(downLoadPath);
//如果文件不存在,退出
File file = new File(downLoadPath);
if(!file.exists()){
return null;
}
try {
//获得文件大小
long fileLength = new File(downLoadPath).length();
System.out.println(new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
response.setContentType("text/html;charset=utf-8"); //设置相应类型和编码
response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));

bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
//定义文件读取缓冲区
byte[] buff = new byte[2048];
int bytesRead;
//把下载资源写入到输出流
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return "/contracts/download_ok";
}


@RequestMapping(value="/toUpload.html")
public String toUpload(Model model){
return "/contracts/upload";
}

@RequestMapping(value="/toDownload.html")
public String toDownload(Model model){

return "/contracts/download";
}


文件下载主要是把它的id也一起显示,适合选择下载。上传一起把name一起传到数据库去。

***************

jsp页面:

<li><a class="upload" href="${ctx}/contracts/toUpload.html"  rel="items" ><span>文件上传</span></a></li>
<li><a class="download" href="${ctx}/contracts/downloadBook.html"  enctype="multipart/form-data" rel="items" ><span>文件下载</span></a></li>


upload.jsp

<form action="${ctx}/contracts/upload.html"  enctype="multipart/form-data" method="post">
<input name="fileId" type="hidden" value="${file.fileId}"/>
<input name="contractsName" class="required" type="text" size="30" value="${file.fileName}" alt="请输入合同名称"/>
<input type="file" name="file" multiple="true">

<input type="submit"  value="上传">

</form>


download.jsp

<c:forEach items="${books}" var="entity">
<a href="${ctx}/contracts/download.html?id=${entity.bookId}">${entity.bookName}</a></br>
</c:forEach>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: