前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >jsp页面上传文件,下载文件,设置下载文件格式和预览文件

jsp页面上传文件,下载文件,设置下载文件格式和预览文件

作者头像
Java架构师必看
发布2021-05-14 11:35:33
2.3K0
发布2021-05-14 11:35:33
举报
文章被收录于专栏:Java架构师必看

jsp页面上传文件,下载文件,设置下载文件格式和预览文件

强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码

jsp页面上传文件

如下是form表单中的上传文件表格,该表格有个id=“addFile”,还有个οnchange="checkFile()事件

代码语言:javascript
复制
<tr height="35px">
	<td width="25%" height="20px" align="right">添加回款记录:</td>
	<td width="75%" height="20px" align="left">
	<input class="easyui-filebox" data-options=" buttonText: '选择文件',prompt:'浏览'"  multiple="true" id="addFile" name="file" style="width:90%" onchange="checkFile()" />
	</td>
</tr>
代码语言:javascript
复制
//easyui 文件框
	$('#addFile').filebox({
    buttonText: '选择文件',  //按钮文本
    buttonAlign: 'right',   //按钮对齐
    //multiple: true,       //是否多文件方式
    onChange: function (e) {
    checkFile();
    }
 });

jsp页面设置上传文件格式

代码语言:javascript
复制
 //控制上传文件格式
function checkFile(){
	var fileTypes = ['.jpg', '.jpeg', '.bmp', '.png', '.gif','.pdf'];
	var filePath = $('#addFfile').textbox('getValue');
	if (filePath != '')
	{
	    var flag = false;
		var fileType = filePath.substring(filePath.lastIndexOf("."));
		if(fileTypes && fileTypes.length>0){
			for (var i = 0; i < fileTypes.length; i++){
			  if(fileTypes[i]==fileType){
			    flag = true;
			     break;
			    }
			   }
			 }if (!flag) {
			  alert('不接受'+fileType+'文件类型上传');
			   $('#addFfile').textbox('setValue', '');
			    return;
			    }
			  }
			}

jsp页面下载文件

首先需要一个下载的方法a标签

代码语言:javascript
复制
formatter : function(value, row, index) {
    return ('<a data-index="' + index + '"  class="chakan"><button type="button" class="download">文件下载</button></a> <a data-index="' + index + '"  class="yulan"><button type="button" class="search">文件预览</button></a>');
}

 文件下载的接口

代码语言:javascript
复制
/**
	  * 文件下载 downAttachment
	  * @throws IOException 
	  */
	 @RequestMapping(value = "/downLoadAttachment",produces = "application/octet-stream;charset=UTF-8",method = RequestMethod.GET)
	 @ResponseBody
	 public ResponseEntity<byte[]> downAttachment(HttpServletRequest request,
	   @RequestParam("filename") String filename,
	   @RequestParam("path") String path) throws IOException {
	   //下载文件路径
	   path = uploadDir +"\\"+path;
	   File file = new File(path);
	   if(!file.exists() || file.length() == 0) {  
	       System.out.println("文件为空!");  
	   }else{ 
	    HttpHeaders headers = new HttpHeaders();
	    //下载显示的文件名,解决中文名称乱码问题
	    String downloadFielName = null;
	    String useragent = request.getHeader("USER-AGENT").toLowerCase();
	          if(useragent.contains("msie")||useragent.contains("like gecko")||useragent.contains("trident")){  
	          //ie11或者win10中用户代理字符串已经修改了,不再是“msie”了,添加了like Gecko,所以加上like gecko判断
	           downloadFielName = URLEncoder.encode(filename , "UTF-8");
	          }else{
	           downloadFielName = new String(filename.getBytes("utf-8"),"iso-8859-1"); 
	          }
	    //通知浏览器以attachment(下载方式)打开图片
	    headers.setContentDispositionFormData("attachment", downloadFielName);
	    //application/octet-stream : 二进制流数据(最常见的文件下载)。
	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
	   }
	   return null;
	 }

文件下载的js代码

代码语言:javascript
复制
var gridPanel = datagrid.datagrid("getPanel");
gridPanel.on("click", "a.chakan", function() {
	var rows = datagrid.datagrid('getSelections');
	var id = rows[0].id;
	var fileName = rows[0].fileName;
	var filePath = rows[0].filePath;
	var fileName = encodeURIComponent(fileName);
	var filePath = encodeURIComponent(filePath);   window.location.href="${ctx}/file/downLoadAttachmentfilename="+fileName+"&path="+filePath;
})

jsp页面预览已下载文件

这个总共分为四个部分

jsp有三个部分,controller层有一个方法

预览下载图片,首先需要一个a标签,我这是图片下载和图片预览写在一个返回值里面

代码语言:javascript
复制
formatter : function(value, row, index) {
    return ('<a data-index="' + index + '"  class="chakan"><button type="button" class="download">文件下载</button></a> <a data-index="' + index + '"  class="yulan"><button type="button" class="search">文件预览</button></a>');
}
								}

要有个div,用来展示文件的,一个大div里面内嵌了一个小div

代码语言:javascript
复制
<div id="imageDiv" class="easyui-dialog" style="display:none;" closed="true">
	<img id="imag" alt="" src="">
</div>

预览图片的js代码:

代码语言:javascript
复制
.on("click", "a.yulan", function() {
	var rows = datagrid.datagrid('getSelections');/*获取选中行的数据*/
	var filePath = rows[0].filePath;
	/* jsp url转义 */
	filePath = encodeURIComponent(filePath);
	$("#imag").attr("src","${ctx}/salesDetails/previewPeacher?filePath="+filePath); 
		var win = $('#imageDiv').dialog({ //创建弹出框
		width : '90%',
		height : '100%',
		modal : true, //遮罩层
		title : '文件预览',
		shadow : true, //阴影
		    buttons : [ {
				text : '关闭',
				iconCls : 'icon-no',
				handler : function() {
					$("#imageDiv").dialog('close');
				}
			}]
		});
			win.dialog('open'); //打开添加对话框
			win.window('center'); //使Dialog居中显示
		})

文件预览的controller接口方法:

代码语言:javascript
复制
/**
 * 图片预览
 * @param request
 * @param response
 * @param filePath
 * @throws IOException
 */
@RequestMapping("/previewPeacher")
public void getImg2(HttpServletRequest request, HttpServletResponse response,String filePath ) throws IOException {
	FileInputStream fis = null;
	OutputStream os = null;
	try {
		fis = new FileInputStream("D:\\hyzn\\"+filePath);
		os = response.getOutputStream();
		int count = 0;
		byte[] buffer = new byte[1024 * 8];
		while ((count = fis.read(buffer)) != -1) {
		os.write(buffer, 0, count);
		os.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try{
			    fis.close();
				os.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • jsp页面上传文件
  • jsp页面设置上传文件格式
  • jsp页面下载文件
  • jsp页面预览已下载文件
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档