springMVC上传下载
利用spring上传下载文件
先添加依赖
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version>
</dependency>
在springMVC配置文件中加入bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>10485760</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean>
上传jsp页面
<link href="<c:url value="/static/css/bootstrap-fileupload.css"/>" rel="stylesheet" type="text/css"/> <script src="<c:url value="/static/js/bootstrap-fileupload.js"/>" type="text/javascript"></script>
<form id="upLoadForm" enctype="multipart/form-data" method="post" action="<c:url value='/qrcAgentQrCodeDetail/upLoad'/>"> <div class="span3"> <div class="control-group"> <label class="control-label">背景图片:</label> <div class="controls "> <div class="fileupload fileupload-new must" data-provides="fileupload"> <span class="btn btn-file"> <i class="icon-upload-alt"></i> <span class="fileupload-new ">PNG格式</span> <span class="fileupload-exists">修改</span> <input type="file" name="fileMap[filePath]" class="default " accept=".PNG"/> </span> <span class="fileupload-preview"></span> <a href="#" class="close fileupload-exists" data-dismiss="fileupload" style="float: none"></a> </div> </div> </div> </div> </form>
上传代码
form
import java.util.HashMap; import java.util.Map; import org.springframework.web.multipart.MultipartFile; public class QRCodeForm { private Map<String, MultipartFile> fileMap = new HashMap<String, MultipartFile>(); public Map<String, MultipartFile> getFileMap() { return fileMap; } public void setFileMap(Map<String, MultipartFile> fileMap) { this.fileMap = fileMap; } }
controller
/** * 图片上传 * @param form * @param ra * @return */ @RequestMapping(value = "/upLoad",method = RequestMethod.POST) public String upLoad(QRCodeForm form,RedirectAttributes ra){ String url = "redirect:/qrcAgentQrCodeDetail/query"; try { qrcAgentQrCodeDetailService.upLoad(form.getFileMap()); ra.addFlashAttribute(Message.SUCCESS, "图片上传成功"); } catch (Exception e) { e.printStackTrace(); ra.addFlashAttribute(Message.ERROR, "图片上传失败"); } return url; }
service
@Override public void upLoad(Map<String, MultipartFile> fileMap)throws IOException { String baseDir = paramService.getSFTPFilePath(); for(Map.Entry<String, MultipartFile> entity:fileMap.entrySet()){ if(entity.getKey().equals("filePath")){ String prefixPath = baseDir + "/QRCode"; String sourceFileName = entity.getValue().getOriginalFilename(); String suffix = sourceFileName.substring(sourceFileName.lastIndexOf(".")+1); String newFileName = new SimpleDateFormat("SSS").format(new Date())+"FILE."+suffix; String filePath = prefixPath+"/"+newFileName; File file = new File(prefixPath); if(!file.exists()){ file.mkdirs(); } OutputStream os = new FileOutputStream(filePath); int len; byte [] bs = new byte[1024]; InputStream inputStream = entity.getValue().getInputStream(); while((len = inputStream.read(bs))!= -1){ os.write(bs,0,len); } os.close(); inputStream.close(); Param param = paramService.getParam(QR_BACKGROUDPATH); param.setStrVal(filePath); qrcAgentQrCodeDetailDao.save(param); } } }
下载jsp页面
<div class="row-fluid"> <div class="span6"> <div class="control-group"> <label class="control-label">资质材料:</label> <div class="controls"> <c:if test="${not empty agent.filePath}"> <a class="btn green" data-rel="fancybox-button" href="<c:url value="/agent/download.html?filePath=${agent.filePath}"/>" <i class="icon-download-alt"></i>点此下载文件 </a> </c:if> <c:if test="${empty agent.filePath}"> <span class="text">未找到资质文件</span> </c:if> </div> </div> </div> </div>
下载代码
@RequestMapping("/download") public String download(String filePath,HttpServletResponse response,RedirectAttributes ra){ try { // path是指欲下载的文件的路径。 File file = new File(filePath); // 取得文件名。 String filename = file.getName(); // 以流的形式下载文件。 InputStream fis = new BufferedInputStream(new FileInputStream(filePath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); ra.addFlashAttribute(Message.ERROR, "下载出错,请稍后"); return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/agent/index"; } return null; }