/** * 下载 * @return */ def download(){ def fileObj = ValuationHistoryForNSQ.get(params["id"]) def file_name = fileObj.getFile_name() def file_type = fileObj.getFile_type() def root_path = fileObj.getRoot_path() def file_path = fileObj.getFile_path() def downloadPath = root_path+file_path+file_name def bis = new BufferedInputStream(new FileInputStream(downloadPath)) def bos = new BufferedOutputStream(response.outputStream) long fileLength = new File(downloadPath).length() response.setCharacterEncoding("UTF-8") response.setContentType("multipart/form-data") String userAgent = request.getHeader("User-Agent").toLowerCase() if ( userAgent.contains( "msie" ) || userAgent.contains( "like gecko" ) ){ // ie for win10 ie edge browser and other systems file_name = URLEncoder. encode (file_name, "UTF-8" ) }else { file_name = new String(file_name.getBytes("UTF-8"), "iso-8859-1") } response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", file_name)) response.setHeader("Content-Length", String.valueOf(fileLength)) byte [] buff = new byte [ 2048 ] int bytesRead while (- 1 ! = (bytesRead = bis.read (buff, 0 , buff. length ))) { bos.write(buff, 0, bytesRead) } bis.close() bos.close() }
/** * 查看图片 * @return */ def look(){ def fileObj = ValuationHistoryForNSQ.get(params["id"]) def file_name = fileObj.getFile_name() def file_type = fileObj.getFile_type() def root_path = fileObj.getRoot_path() def file_path = fileObj.getFile_path() def downloadPath = root_path+file_path+file_name //Read the local image input stream FileInputStream inputStream = new FileInputStream(downloadPath); int i = inputStream.available(); //byte array is used to store image byte data byte [] buff = new byte [i]; inputStream.read(buff); //Remember to close the input stream inputStream.close(); //Set the content type of the response sent to the client response.setContentType( "image/*" ); OutputStream out = response.getOutputStream(); out.write(buff); //Close the response output stream out.close(); }
View image front desk method:
<a href="javascript:void(0)" class="btn btn-xs btn-primary btn-outline" onclick="look(${it?.id})">查看</a>
function look(id) { var srcPath = '/valuationHistoryForNSQ/look?id='+id var imgPath = '<img src="'+srcPath+'" width="800px" height="500px">' layer.open({ type: 1 //Page层类型 ,area: ['800px', '542px'] , title : 'View' , scrollbar : false //Block the browser scroll bar , shade : 0.6 //mask transparency , maxmin : false //Allow full screen minimization , anim : 5 //The animation form of 0-6, -1 is not enabled ,content: imgPath }); }
grails file download, pay attention to the Chinese garbled problem, my file path and file name are found from the database.
I use win10 system, it is worth noting the difference between win10 ie and edge and other browsers