当前位置: 代码迷 >> 综合 >> SpringMVC 上传下载
  详细解决方案

SpringMVC 上传下载

热度:45   发布时间:2023-11-25 06:43:30.0

下面介绍一下SpringMVC对文件的上传和下载,
注意:上传文件和下载文件不能使用Ajax请求,必须是form表单提交

上传

springMVC配置文件的配置:

 <!-- 上传文件解释器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize" value="104857600" /><property name="maxInMemorySize" value="4096" /><property name="defaultEncoding" value="UTF-8"></property>
</bean>

Java后台

  • contorller层:
    /*** 上传文件* @param file* @param request* @param session* @return*/@RequestMapping("upLoadFile")@ResponseBodypublic ResponseEntity upLoadFile(@RequestParam("addUploadFile") CommonsMultipartFile file,HttpServletRequest  request,HttpSession session){Date date=new Date();SimpleDateFormat sdfTime=new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");try{List<Resource> resourceList=resourceService.findByResourceName(request.getParameter("addResourceName"));if(resourceList.size()!=0){
   //判断用户名是否存在return ResponseEntity.status(ResponseVoConstant.BADREQUEST).data(null).errorMessage(MessageUtil.getMessageValue("PROJECT_NAME_ALREADY_EXIST"));}       String path="/PMS_Resource/"+request.getParameter("addProjectId");//文件保存路径File newfile=new File(path,file.getOriginalFilename());if (!newfile.exists()) {    //判断文件的路径是否存在 newfile.mkdirs();  //如果文件不存在 在目录中创建文件夹 这里要注意mkdir()和mkdirs()的区别 }  file.transferTo(newfile); Resource resource=new Resource();resource.setResourceName(request.getParameter("addResourceName"));//资源名resource.setResourceAddress(newfile.getPath());resource.setPorjectId(Integer.parseInt(request.getParameter("addProjectId")));//项目IDresource.setUploadUserId(Integer.parseInt(session.getAttribute("userId").toString()));resource.setUploadTime(sdfTime.parse(sdfTime.format(date)));resource.setResourceBrief(request.getParameter("addResourceBrief"));//资源简介resourceService.save(resource);//保存资源信息}catch (Exception e) {return ResponseEntity.status(ResponseVoConstant.BADREQUEST).data(null).errorMessage(MessageUtil.getMessageValue("SAVE_FAIL"));}return ResponseEntity.status(ResponseVoConstant.OK).data(null).errorMessage(MessageUtil.getMessageValue("UPLOAD_SUCCESS")); }

此时文件就保存到这个路径下:

String path="/PMS_Resource/"+request.getParameter("addProjectId");//文件保存路径

前台界面代码

  • HTML:
<form id="addResourceForm" method="post" class="form-horizontal"><div class="form-group"><label for="constantTypeName" class="col-sm-3 control-label">所属项目编号</label><select class="form-control" id="addProjectId"name="addProjectId"></select><!-- <div class="col-sm-9"><input type="text" class="form-control" id="addProjectId"name="addProjectId" readonly></div> --></div><div class="form-group"><label for="constantTypeName" class="col-sm-3 control-label">资源名称</label><div class="col-sm-9"><input type="text" class="form-control" id="addResourceName"name="addResourceName"></div></div><div class="form-group"><label for="constantTypeName" class="col-sm-3 control-label">资源上传</label><div class="col-sm-9"><input type="file" class="form-control" id="addUploadFile" name="addUploadFile" onchange="checkResourceSize(this)"></div></div><div class="form-group"><label for="constantTypeName" class="col-sm-3 control-label">资源简介</label><div class="col-sm-9"><textarea  class="form-control" id="addResourceBrief"name="addResourceBrief"></textarea></div></div><div class="form-group"><div class="col-sm-4 col-sm-offset-8" style="text-align: right"><button type="button" id="saveResourceBtn"class="btn btn-primary" onclick="addResource()">保存</button><button type="button" class="btn btn-default"data-dismiss="modal">关闭</button></div></div><div id="modalResourceTip"></div></form>
  • js代码:
function addResource() {
    if($('#addResourceName').val()==''){$("#modalResourceTip").append("<div id=\"resourceAlert\" class=\"alert alert-danger\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>资源名不能为空</div>");setTimeout(function(){
    $("#resourceAlert").remove()         },2000);return false;  }if( $('#addUploadFile').val().trim() ==""){$("#modalResourceTip").append("<div id=\"resourceAlert\" class=\"alert alert-danger\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>请选择上传需要上传的资料</div>");setTimeout(function(){
    $("#resourceAlert").remove()         },2000);return false;  }if( $('#addResourceBrief').val().trim() ==""){$("#modalResourceTip").append("<div id=\"resourceAlert\" class=\"alert alert-danger\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>请填写资源简介</div>");setTimeout(function(){
    $("#resourceAlert").remove()         },2000);return false;  }$("#addResourceForm").ajaxSubmit({url: "../../resource/upLoadFile",type: "post",enctype: 'multipart/form-data',// iframe: true,dataType:'json',success: function (data){
    if(data.status=="2000"){$("#addResourceModal").modal('hide');//显示form模态框getData(1, 10);//重新加载数据}else{$("#modalResourceTip").append("<div id=\"resourceAlert\" class=\"alert alert-danger\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>上传资源失败了,"+data.errorMessage+"</div>");setTimeout(function(){
    $("#resourceAlert").remove();       },2000);}},error: function (data){
    $("#modalResourceTip").append("<div id=\"resourceAlert\" class=\"alert alert-danger\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>上传资源失败了,服务器出现了问题,请稍后重试</div>");setTimeout(function(){
    $("#resourceAlert").remove();        },2000);}})}/** * 检查文件大小 * @param ele * @returns */
function checkResourceSize(ele){
    if((ele.files[0].size / 1024/1024).toFixed(2)>30){$("#saveResourceBtn").attr("disabled","disabled");$("#modalResourceTip").append("<div id=\"resourceAlert\" class=\"alert alert-danger\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>上传文件的大小不能超过30M</div>");return false;  }else{$("#saveResourceBtn").removeAttr("disabled");//将按钮可用 setTimeout(function(){
    $("#resourceAlert").remove()         },1000);}}

这样上传文件就完成了!!

演示图片:

这里写图片描述
就上传到指定的路径下了
这里写图片描述

下载

Java后台:

/*** 下载* @param request* @param response* @return* @throws Exception*/@RequestMapping("downLoad")@ResponseBodypublic ResponseEntity downLoad(HttpServletRequest  request,HttpServletResponse response) throws Exception{FileInputStream fis =null;BufferedInputStream bis =null;try { //通过资源ID获取实体类Resource retResource=resourceService.findResourceById(Integer.parseInt(request.getParameter("resourceId")));File file = new File(retResource.getResourceAddress());String path=retResource.getResourceAddress();//获取文件路径String fileName=path.substring(path.lastIndexOf("\\")+1);//截取文件名if(file.exists()){response.setContentType("application/octet-stream");response.addHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("utf-8"),"iso-8859-1"));response.setHeader("Content-Length", String.valueOf(file.length()));byte[] buffer = new byte[1024];fis = new FileInputStream(file);bis = new BufferedInputStream(fis);OutputStream os =response.getOutputStream();int i =bis.read(buffer);while (i!=-1) {os.write(buffer, 0, i);i=bis.read(buffer);}}  else{return ResponseEntity.status(ResponseVoConstant.BADREQUEST).data(null).errorMessage(MessageUtil.getMessageValue("DOWNLOAD_FIAL"));   }} catch (Exception e) {return ResponseEntity.status(ResponseVoConstant.BADREQUEST).data(null).errorMessage(MessageUtil.getMessageValue("DOWNLOAD_FIAL"));      }finally {bis.close();fis.close();}return ResponseEntity.status(ResponseVoConstant.OK).data(null).errorMessage(MessageUtil.getMessageValue("DOWNLOAD_SUCCESS"));   }/*** 通过资源ID检查文件是否存在* @param resource* @param request* @return* @throws Exception */@RequestMapping("checkFileByResourceId")@ResponseBodypublic ResponseEntity checkFileByResourceId(@RequestBody Resource resource,HttpServletRequest request) throws Exception{Resource retResource=resourceService.findResourceById(resource.getResourceId());File file = new File(retResource.getResourceAddress());if(file.exists()){
   //判断文件是否存在return ResponseEntity.status(ResponseVoConstant.OK).data(null).errorMessage(MessageUtil.getMessageValue("FILE_EXIST"));  }else {return ResponseEntity.status(ResponseVoConstant.BADREQUEST).data(null).errorMessage(MessageUtil.getMessageValue("FILE_NO_EXIST"));  }}

前台代码

  • HTML
    <form id="updateResourceForm" method="post" class="form-horizontal"><div id="downloadResourceTip"></div><div class="form-group"><div class="col-sm-4 col-sm-offset-8" style="text-align: right"><button type="button" id="downloadResourceBtn"class="btn btn-primary" onclick="">下载</button><button type="button" class="btn btn-default"data-dismiss="modal">关闭</button></div></div></form>
  • js代码
/** * 下载资源 * @param resourceId * @returns */
function downloadResource(resourceId) {
    $("#downloadForm").remove();//移除之前下载时产生的form,防止冗余var form=$("<form id='downloadForm'>");//定义一个form表单 form.attr("style","display:none");  form.attr("target","");  form.attr("method","post");  form.attr("action","../../resource/downLoad");  var inputResourceId=$("<input>");  inputResourceId.attr("type","text");  inputResourceId.attr("name","resourceId");  inputResourceId.attr("value",resourceId);  $("body").append(form);//将表单放置在web中 form.append(inputResourceId);  form.submit();//表单提交 
}//确认资源能否下载function checkResourceStatus(resourceId) {
    $("#downloadResourceAlert").remove();$("#downloadResourceBtn").removeAttr("disabled");//将按钮可用 $("#downloadResourceBtn").removeAttr("onclick");//移除下载事件$.ajax({url : '../../resource/checkFileByResourceId', type: "POST",contentType:'application/json',data : JSON.stringify({"resourceId":resourceId}),success : function(result) {
    if(result.status=="2000"){$("#downloadResourceTip").append("<div id=\"downloadResourceAlert\" class=\"alert alert-success\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>资源正常,可以正常下载</div>");$("#downloadResourceBtn").attr("onclick","downloadResource("+resourceId+")");}else{$("#downloadResourceTip").append("<div id=\"downloadResourceAlert\" class=\"alert alert-danger\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>"+result.errorMessage+"</div>"); $("#downloadResourceBtn").attr("disabled","disabled");}},error : function() {
    $("#downloadResourceTip").append("<div id=\"downloadResourceAlert\" class=\"alert alert-danger\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>服务器出现了问题,暂时无法下载,请稍后重试</div>");   $("#downloadResourceBtn").attr("disabled","disabled");}});

这样下载就完成了,可以把刚刚上传的文件下载下来:

演示

这里写图片描述

  相关解决方案