SoFunction
Updated on 2025-04-14

Java implements the preview and download functions of file pictures

Preview and download of Java implementation files (pictures)

    @ApiOperation("Access File")
    @GetMapping("/download/{name}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        // Dynamically obtain the image storage location        // String path = getUploadPath();//Get the current system path        String path = upload;
        String imagePath = path +  + name;
        if (!new File(imagePath).exists()) {
            return;
        }
        if (("jpg") || ("png") || ("gif") || ("jpeg")) {
            //Do not set Content-Disposition during preview            ("image/jpeg;charset=utf-8");//picture        }else {
            //download        ("application/octet-stream");//document        ("Content-Disposition", "inline; filename=" + (name, "UTF-8"));
        }
        ServletOutputStream outputStream = ();
        (((path).resolve(name)));
        ();
        ();
    }

Note: If you have struck a trap, the file name cannot be included with *, and the file name will be included with * will be reported.

Download files in the resources directory through mvc and hutool toolsets, pay attention to the packages introduced

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;

@RestController
@RequestMapping("/api/files")
public class FileDownloadController {

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile() {
        String fileName = ""; // File name to download        
        try {
            // Load the file from the resources directory            ClassPathResource resource = new ClassPathResource(fileName);
            
            if (!()) {
                return ().build();
            }

            // Set response header            HttpHeaders headers = new HttpHeaders();
            (HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + ());

            // Return the file as a response            return ()
                    .headers(headers)
                    .contentType(.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (IOException e) {
            return (HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}

Method supplement

Method 1:

This code snippet shows how to implement preview and download files in Spring Boot. Through HttpServletRequest and HttpServletResponse, determine whether to preview or download based on the request parameters, and set the corresponding content type and Content-Disposition. The file path is in a fixed directory, and the file content is read and the response stream is written.

Specific as follows

package ;

import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;

/**
 * @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 = ("fileName");
        //type.p preview, d download        String type = ("type");
        ();
        ("UTF-8");

        File file = new File("C:\\Users\\long\\Desktop\\" + fileName);
        FileInputStream fis = new FileInputStream(file);

        if ("d".equalsIgnoreCase(type)) {
            //download            ("application/octet-stream");
            ("Content-Disposition", "attachment;filename*=utf-8''" + () + ((".")));

        } else {
            //Do not set Content-Disposition during preview//            ("application/octet-stream");
//            ("text/html;charset=UTF-8");
//            ("Content-Disposition","inline;filename=" + () + ((".")));
        }
        OutputStream os = ();
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = (bytes)) != -1) {
            (bytes, 0, length);
        }
        ();
        ();
    }


}

Method 2:

Java implements online preview and download of pictures or files

Complete code

@GetMapping("/downFile")
    public void downFile(HttpServletResponse response, HttpServletRequest request) {
        try {
// File file = new File("C:\\Users\\hnsh\\Pictures\\Tieshankui.png");            File file = new File("F:\\BaiduNetdiskDownload\\activitiTutorial (1).pdf");
            String filename = ();
            String fileType = ((".") + 1);

            // Download the file in stream form.            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[1024];
            int len = 0;
            // Clear response            ();
            // Set the response header            // Solve cross-domain            ("Access-Control-Allow-Origin", "*");
            boolean b = "jpg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType);
            // Picture preview            if (b) {
                ("image/" + fileType);
            } else if ("pdf".equalsIgnoreCase(fileType)) {
                // pdf preview                ("application/pdf");
            } else {
                // Download directly                ("application/text;chartset=utf-8");
                ("Content-Disposition", "attachment;filename=" + (filename, "UTF-8"));
                ("Content-Length", "" + ());
            }
            OutputStream toClient = new BufferedOutputStream(());
            int a = 0;
            while ((len = (buffer)) != -1) {
                a = len + a;
                (buffer, 0, len);
            }
            ();
            ();
        } catch (IOException ex) {
            ();
        }
    }

This is the article about Java implementing the preview and download function of file pictures. For more related Java picture preview and download content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!