本文主要是介绍Java实现文件图片的预览和下载功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...
Java实现文件(图片)的预览和下载
@ApiOperation("访问文件") @GetMapping("/download/{name}") public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException { //动态获取图片存放位置 // String path = getUploadPath();//获取当前系统路径 String path = upload; String imagePath = path + File.separator + name; if (!new File(imagePath).exists()) { return; } if (name.endsWith("jpg") || name.endsWith("png") || name.endsWith("gif") || name.endsWith("jpeg")) { //预览时不需设置Content-Disposition response.setContentType("image/jpeg;charset=utf-8");//图片 }else { //下载 response.setContentType("application/octet-stream");//文件 response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(name, "UTF-8")); } ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(Files.readAllBytes(Paths.get(path).resolve(name))); outputStream.flush(); outputStream.close(); }
注意:踩过的坑,文件名不可以带*号,带*会报java.io.FileNotFoundException
通过mvc与hutool工具集下载在resources目录下的文件,注意引入的包
package com.example.controller; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.nio.file.Files; @RestController @RequestMapping("/api/files") public class FileDownloadController { @GetMapping("/download") public ResponseEntity<Resource> downloadFile() { String fileName = "example.txt"; // 要下载的文件名 try { // 从 resources 目录加载文件 ClassPathResource resource = new ClassPathResourcphpe(fileName); if (!resource.exists()) { return ResponseEntity.notFound().build(); } // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename()); // 返回文件作为响应 return ResponseEn编程tity.ok() .headers(headers) .contentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM) .body(resource); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } }
方法补充
方法一:
该代码段展示了如何在Spring Boot中实现文件的预览和下载功能。通过HttpServletRequest和HttpServletResponse,根据请求参数判断是预览还是下载,并设置相应的内容类型和Content-Disposition。文件路径为固定目录下,读取文件内容并写入响应流。
具体如下
package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; /** * @author long * @version 1.0.0 * @ClassName FileController * @Description TODO * @createTime 2022.03.18 18:47 */ @RestController @RequestMapping("/demo") public class FileController { @GetMapping("/file") public void filePreviewOrDownload(HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = request.getParameter("fileName"); //type. p预览,d下载 String type = request.getParameter("type"); response.reset(); response.setCharacterEncoding("UTF-8"); File file = new File("C:\\Users\\long\\Desktop\\" + fileName); FileInputStream fis = new FileInputStream(file); if ("d".equalsIgnoreCase(type)) { //下载 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."))); } else { //预览时不需设置Content-Disposition // response.setContentType("application/octet-stream"); // response.setContentType("text/html;charset=UTF-8"); // http://www.chinasem.cn response.setHeader("Content-Disposition","inline;filename=" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."))); } OutputStream os = response.getOutputStream(); byte[] bytes = new byte[1024]; int length = 0; while ((length = fis.read(bytes)) != -1) { os.write(bytes, 0, length); } os.close(); fis.close(); } }
方法二:
Java 实现图片或文件在线预览及下载
完整代码
@GetMapping("/downFile") public void downFile(HttpServletResponse response, HttpServletRequest request) { try { // File file = new File("C:\\Users\\hnsh\\Pictures\\铁山靠.png"); File file = new File("F:\\BaiduNetdiskDownload\\activiti教程 (1).pdf"); China编程 String filename = file.getName(); String fileType = filename.substring(filename.indexOf(".") + 1); // 以流的形式下载文件。 FileInputStream fileInputStream = new FileInputStream(file); InputStream fis = new BufferedInputStream(fileInputStream); byte[] buffer = new byte[1024]; int len = 0; // 清空response response.reset(); // 设置response的Header // 解决跨域 response.addHeader("Access-Control-Allow-Origin", "*"); boolean b = "jpg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType); // 图片预览 if (b) { response.setContentType("image/" + fileType); } else if ("pdf".equalsIgnoreCase(fileType)) { // pdf 预览 response.setContentType("application/pdf"); } else { // 直接下载 response.setContentType("application/text;chartset=utf-8"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); response.addHeader("Content-Length", "" + file.length()); } OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); int a = 0; while ((len = fis.read(buffer)) != -1) { a = len + a; toClient.write(buffer, 0, len); } China编程 toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } }
到此这篇关于Java实现文件图片的预览和下载功能的文章就介绍到这了,更多相关Java图片预览和下载内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!
这篇关于Java实现文件图片的预览和下载功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!