SpringBoot项目上传、下载文件

项目中遇到,记录一下。

上传文件

HTML页面
<div class="file-loading">
	<input id="test_file" type="file" class="file-loading" accept="image/*,.pdf,.xlsx,.xls,.docx,.doc" name="file">
</div>
JS

这里用的是bootStrap fileinput组件

$("#test_file").fileinput({
        uploadUrl: "../isv/agasdhdgjdfghdh",//"/file-upload-single/1",//上传的地址
        language:'zh',//设置语言,中文
        dropZoneTitle: '可以将文件拖放到这里 …不支持多文件上传',
        allowedFileExtensions: ['jpg','png','xlsx','pdf','xls','doc','docx'],//接收的文件后缀
        showUpload: false, //是否显示上传按钮
        showRemove: true, //显示移除按钮
        showPreview: true, //是否显示预览
        dropZoneEnabled: true,//是否显示拖拽区域,
        showCaption: true,//是否显示文件标题,默认为true
        uploadAsync: true, //默认异步上传
        browseClass: "btn btn-primary", //文件选择器/浏览按钮的CSS类。默认为btn btn-primary
        minFileCount: 1, //每次上传允许的最少文件数。如果设置为0,则表示文件数是可选的。默认为0
        maxFileCount: 1, //每次上传允许的最大文件数。如果设置为0,则表示允许的文件数是无限制的。默认为0
        previewFileIcon: "<i class='fa fa-file-text'></i>",//当检测到用于预览的不可读文件类型时,将在每个预览文件缩略图中显示的图标。默认为<i class="glyphicon glyphicon-file"></i>  
        msgInvalidFileExtension: "不正确的文件扩展名 {name}. 只支持 {extensions}的文件扩展名.",
        enctype: 'multipart/form-data',
	}).on("filebatchselected", function(e, files) {        
        $(this).fileinput("upload");             // 文件选择完直接调用上传方法。
    });
Controller
System.getProperty(“user.dir”);参数即可获得项目相对路径。(ps:不知道是不是springboot内嵌tomcat容器的原因,用网上的request.getServletContext().getRealPath("/")方法获得的路径不是项目路径,而是c盘下一个tomcat目录路径)
	@RequestMapping("/saveFile")
	@ResponseBody
	public JSONObject saveFile(@RequestParam("file") MultipartFile file) {
		//获取文件名
		String fileName = file.getOriginalFilename();
		//文件后缀名
		String subffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		//文件保存进来,我给他重新命名,数据库保存有原本的名字,所以输出的时候再把他附上原本的名字就行了。
		String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		//获取项目绝对路径
		String filePath = System.getProperty("user.dir")+"\\src\\main\\resources\\templates\\files";
		File newFile = new File(filePath);
		//保存文件
		file.transferTo(new File(newFile+"\\"+newFileName+"."+subffix));
        //保存路径
		String realpath = newFile+"\\"+newFileName+"."+subffix;
        //返回路径
		josn = getJsonResult(true, realpath ,StateParameter.SUCCESSFUL_MSG);
			
		return josn;
	}
	

下载文件

HTML页面
用 bootStrap-Table 加的表格按钮,按钮绑触发事件,没有HTML代码	
JS
window.operateEvents={
		"click #file_list_tab_down_load":function (e, value, row, index) {//下载
			//参数可以在from里拼input标签,设置隐藏提交from的时候传参数
			//这里传的是文件信息在数据库里的id,方便下载
			var $eleForm = $("<form method='post'><input name='fileId' id='file_id' value="+row.id+" style='display: none;'></form>");
			//请求路径
			$eleForm.attr("action","http://localhost:8080/isv/downFile");
			//body里添加进去这个from
			$(document.body).append($eleForm);
			//提交表单,实现下载
			$eleForm.submit();
		}
		
	}
Controller
	/**
	 * 下载附件
	 * @param res
	 * @param id
	 */
	@RequestMapping( value = "/downFile")
	@ResponseBody
	public void downFile(HttpServletResponse res,@RequestParam(name = "fileId") Integer id ) {
		//参数列表里 RequestParam的name属性要和from中拼接的input里的name要一样,不然接不到参数
		//文件详细信息,路径,文件名,改完之后的文件名等等
		FileObject fileObject = iRepairOrderService.getOneFileObject(id);
		for(int x=0;x<2;x++) {
			res.setHeader("content-type", "application/octet-stream");
			res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");  
			try {
				//解决中文文件名乱码,不然文件名会变成下划线
				res.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"",URLEncoder.encode(fileObject.getFileName(), "utf-8") ));
			} catch (UnsupportedEncodingException e1) {
				System.err.println(e1.getMessage());
				e1.printStackTrace();
			}  
			res.setHeader("Pragma", "no-cache");  
			res.setHeader("Expires", "0");  
		    res.setContentType("application/octet-stream;charset=utf-8");
		    byte[] buff = new byte[1024];
		    BufferedInputStream bis = null;
		    OutputStream os = null;
		    try {
		      os = res.getOutputStream();
		      //文件在项目中的绝对路径
		      bis = new BufferedInputStream(new FileInputStream( 
		                new File(System.getProperty("user.dir")+"\\src\\main\\resources\\templates\\files\\" + fileObject.getNewFileName())));
		      int i = bis.read(buff);
		 
		      while (i != -1) {
		        os.write(buff, 0, buff.length);
		        os.flush();
		        i = bis.read(buff);
		      }
		    } catch ( IOException e ) {
		      e.printStackTrace();
		    } finally {
		      if (bis != null) {
		        try {
		          bis.close();
		        } catch (IOException e) {
		          e.printStackTrace();
		        }
		      }
		    }
		  }
		}
	    
发布了9 篇原创文章 · 获赞 3 · 访问量 627

猜你喜欢

转载自blog.csdn.net/weixin_44657749/article/details/102778718