JavaWeb;SpringMVC;SpringBoot上传和下载文件实例(只允许上传特定格式文件)

更改部分业务逻辑代码,因为涉及隐私

文件上传前端,使用easyUI:

<input class="easyui-filebox" name="${item.dictCode }" style="width:150px;" data-options="buttonText:'附件',accept:'image/jpeg,image/jpg,image/png,application/pdf'">

保存文件后端:

//自定义允许上传的文件格式数组
private String[] types = {"pdf","jpg","jpeg","png"};

@RequestMapping("saveInfo")
	public Message saveInfo(TStudentAttach studentAttach,HttpServletRequest request,MultipartFile[] prizesFile) throws Exception {
		Message msg = new Message();
		msg.setCode(0);
		msg.setMsg("没有上传任何文件!");
		String idstr = request.getParameter("studentId");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Iterator<String> itr =  multipartRequest.getFileNames();
		if(idstr != null && idstr != "") {	
		TStudent student = studentMapper.selectByPrimaryKey(Integer.valueOf(idstr));	
		String idnumber = student.getStudentIdnumber();
		//保存多个文件 荣誉 路径为全局变量
		String prizeFilePath = CommUtil.UPLOAD_PATH+CommUtil.UPLOAD_PATH_EXSOLDIER_PRIZE+idnumber+"\\";
		TStudentAttach tea = new TStudentAttach();
		try {		
			while(itr.hasNext()){
                //前台input标签中的name值 这样是为了使name和文件一一对应
                String inputName = itr.next();
                //根据name获取对应文件
				MultipartFile multipartFile = multipartRequest.getFile(inputName);
				String originalFilename = multipartFile.getOriginalFilename();
				boolean flag = isAccept(originalFilename,this.types);
				if(!flag) {
					continue;
				}
				//存在文件的
				if(!"".equals(originalFilename)) {
					String newFileName = getNewFileName(multipartFile);
					saveFile(multipartFile, prizeFilePath, newFileName);
					tea.setAttachKind(inputName);
					tea.setStudentId(student.getSoldierId());
					tea.setAttachUrl(CommUtil.UPLOAD_PATH_EXSOLDIER_PRIZE+idnumber+"\\"+newFileName);
					studentAttachMapper.insertSelective(tea);	
					msg.setCode(1);
					msg.setMsg("添加成功!");
				}
			}
		} catch (Exception e) {
			msg.setCode(0);
			msg.setMsg("出现异常,添加失败!请尝试刷新页面后重新操作");
			return msg;
		}
					
		}
		return msg;
    }
    


    /**
	* @Title: 
	* @Description: TODO(保存springmvc上传的文件)
	* @param 
	* @return void 返回类型
	*/
	public void saveFile(MultipartFile mtfile,String filePath,String newFileName) throws Exception{
		File file = new File(filePath);
		if(!file.exists()) {
			file.mkdirs();
		}
		mtfile.transferTo(new File(filePath+newFileName));
    }
    

    /**
	* @Title: 
	* @Description: TODO(组建新文件名)
	* @param 
	* @return String 返回类型
	*/
	public String getNewFileName(MultipartFile mtfile) {
		String fileName = mtfile.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		String newFileName = System.currentTimeMillis()+"."+suffix;
		return newFileName;
    }
    
    /**
	* @Title: 
	* @Description: TODO(判断是否是允许上传的文件格式,判断后缀)
	* @param 
	* @return boolean 返回类型
	*/
	public boolean isAccept(String fileName,String[] suffixes) {
		int count = 0;
		for (String suffix : suffixes) {
			if(fileName.endsWith(suffix)) {
				count++;			
			}			
		}
		if(count > 0) {
			return true;
		}
		return false;
	}

下载文件前台:

<a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'icon-save'"  onclick="downLoad(${attachId })">下载</a>
<script>
    //下载
        function downLoad(attachId){
            if(attachId != null){
                location.href="<%=basePath%>attach/downloadFile?attachId="+attachId;			
            }
        }
</script>

下载文件后台:

/**
	* @Title: 
	* @Description: TODO(下载文件)
	* @param 
	* @return void 返回类型
	*/
	@RequestMapping("downloadFile")
	public void downloadFile(Integer attachId,HttpServletResponse response) throws Exception {
		TStudentAttach attach = studentAttachMapper.selectByPrimaryKey(attachId);
		String url = attach.getAttachUrl();
        //文件真实路径
		url = CommUtil.UPLOAD_PATH+url;
		InputStream bis = new BufferedInputStream(new FileInputStream(new File(url)));
		byte[] buffer = new byte[bis.available()];
		bis.read(buffer);
        bis.close();
        //文件名 根据需要改
		String fileName = url.substring(65);
		response.reset();
		//转码,免得文件名中文乱码  
		fileName = URLEncoder.encode(fileName,"UTF-8");  
        //设置文件下载头  
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);    
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型    
        response.setContentType("multipart/form-data");   
        OutputStream out = new BufferedOutputStream(response.getOutputStream());  
		out.write(buffer);
		out.flush();
		out.close();	
	}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值