[Java]上传下载预览文件工具类

上传下载预览文件工具类:

文件上传以及下载:

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class MultipartFileUtils {

    /**
     * 单个文件上传
     * @param
     * @param fileName
     * @param filePath
     */
    public static void upFile(File uploadFile,String fileName,String filePath){

        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        FileInputStream is = null;
        BufferedInputStream bis = null;
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
        }
        File f = new File(filePath+"/"+fileName);
        try {
            is = new FileInputStream(uploadFile);
            bis = new BufferedInputStream(is);
            fos = new FileOutputStream(f);
            bos = new BufferedOutputStream(fos);
            byte[] bt = new byte[4096];
            int len;
            while((len = bis.read(bt))>0){
                bos.write(bt, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

            try {
                if(null != bos){
                    bos.close();
                    bos = null;}
                if(null != fos){
                    fos.close();
                    fos= null;
                }
                if(null != is){
                    is.close();
                    is=null;
                }

                if (null != bis) {
                    bis.close();
                    bis = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    /**
     * 单个文件上传
     * @param is
     * @param fileName
     * @param filePath
     */
    public static void upFile(InputStream is,String fileName,String filePath){

        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
        }
        File f = new File(filePath+"/"+fileName);
        try {
            bis = new BufferedInputStream(is);
            fos = new FileOutputStream(f);
            bos = new BufferedOutputStream(fos);
            byte[] bt = new byte[4096];
            int len;
            while((len = bis.read(bt))>0){
                bos.write(bt, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

            try {
                if(null != bos){
                    bos.close();
                    bos = null;}
                if(null != fos){
                    fos.close();
                    fos= null;
                }
                if(null != is){
                    is.close();
                    is=null;
                }

                if (null != bis) {
                    bis.close();
                    bis = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }








    /**
     * @param request
     * @param response
     * @param downloadFile 下载文件完整路径
     * @param fileName 下载文件名(带文件后缀)
     */
    public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String downloadFile, String fileName) {

        BufferedInputStream bis = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        try {
            File file=new File(downloadFile); //:文件的声明
            is = new FileInputStream(file);  //:文件流的声明
            os = response.getOutputStream(); // 重点突出
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(os);

            if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                fileName = new String(fileName.getBytes("GB2312"),"ISO-8859-1");
            } else {
                // 对文件名进行编码处理中文问题
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
            }

            response.reset(); // 重点突出
            response.setCharacterEncoding("UTF-8"); // 重点突出
            response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
            // inline在浏览器中直接显示,不提示用户下载
            // attachment弹出对话框,提示用户进行下载保存本地
            // 默认为inline方式
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            //  response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出
            int bytesRead = 0;
            byte[] buffer = new byte[4096];// 4k或者8k
            while ((bytesRead = bis.read(buffer)) != -1){ //重点
                bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            // 特别重要
            // 1. 进行关闭是为了释放资源
            // 2. 进行关闭会自动执行flush方法清空缓冲区内容
            try {
                if (null != bis) {
                    bis.close();
                    bis = null;
                }
                if (null != bos) {
                    bos.close();
                    bos = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
                if (null != os) {
                    os.close();
                    os = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 文件下载
     * @param response
     * @param downloadFile 文件的路径
     * @param showFileName 下载后显示的文件名称
     */
    public static void downloadFile(HttpServletResponse response, String downloadFile, String showFileName) {

        BufferedInputStream bis = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        try {
            File file=new File(downloadFile); //:文件的声明
            String fileName=file.getName();
            is = new FileInputStream(file);  //:文件流的声明
            os = response.getOutputStream(); // 重点突出
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(os);
            // 对文件名进行编码处理中文问题
            fileName = java.net.URLEncoder.encode(showFileName, "UTF-8");// 处理中文文件名的问题
            fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
            response.reset(); // 重点突出
            response.setCharacterEncoding("UTF-8"); // 重点突出
            response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
            // inline在浏览器中直接显示,不提示用户下载
            // attachment弹出对话框,提示用户进行下载保存本地
            // 默认为inline方式
            response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = bis.read(buffer)) != -1){ //重点
                bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        } finally {
            // 特别重要
            // 1. 进行关闭是为了释放资源
            // 2. 进行关闭会自动执行flush方法清空缓冲区内容
            try {
                if (null != bis) {
                    bis.close();
                    bis = null;
                }
                if (null != bos) {
                    bos.close();
                    bos = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
                if (null != os) {
                    os.close();
                    os = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex.getMessage());
            }
        }
    }

}

上传调用示例:

public HashMap<String,Object> uploadFile(MultipartFile uploadFile) throws IOException {
        long time = new Date().getTime();
        HashMap<String,Object> hashMap = new HashMap<>(3);
        String originalFilename = uploadFile.getOriginalFilename();
        int pos = originalFilename.lastIndexOf(".");
        if(pos == -1){
            return hashMap;
        }
        String name = time+uploadFile.getOriginalFilename();
        InputStream inputStream = uploadFile.getInputStream();
        MultipartFileUtils.upFile(inputStream,name,filepath);
        String path  = filepath+""+name;
        hashMap.put("path",path);
        String str = name.substring(0, name.indexOf("."));
        hashMap.put("fileName",str);
        hashMap.put("originalName",uploadFile.getOriginalFilename());
        return hashMap;
    }

下载调用示例:(前端直接打开这个页面)

	@GetMapping("/downloadFile")
    private AjaxResult downloadFile(HttpServletRequest request,
                              HttpServletResponse response,
                              @RequestParam("path") String path,
                              @RequestParam("originalName") String originalName){
        MultipartFileUtils.downloadFile(request,response,path,originalName);
        return AjaxResult.success();
    }


文件预览

文件预览 application.yml:

file:
  staticAccessPath: /Users/apple/file/**
  uploadFolder: /Users/apple/file/
  upload:
    url: /Users/apple/file/ 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyWebAppConfiguration extends WebMvcConfigurationSupport {
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
        super.addResourceHandlers(registry);
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java S3是Amazon Simple Storage Service(简称S3)的Java开发工具包(SDK)。它可以帮助开发者在Java应用程序中实现对S3存储桶中的文件进行预览。 要实现文件预览功能,首先需要确保已在Java项目中引入S3的Java SDK。然后,通过SDK提供的API,可以对S3存储桶中的文件进行读取和处理。 实现文件预览的基本步骤如下: 1. 首先,建立与S3的连接。使用SDK提供的CredentialProvider,提供S3的访问凭证,包括访问密钥和密钥ID。 2. 然后,使用S3Client对象来访问S3存储桶。通过指定存储桶名称和文件路径,可以获取到目标文件的对象。 3. 接下来,根据文件的内容类型来确定文件预览方式。例如,如果文件是图片,可以使用图像处理库来生成缩略图或将其显示在页面上;如果是文本文件,可以读取文件内容并在页面上显示。 4. 将处理后的文件预览展示在用户界面上。可以使用Java Swing、JavaFX或Web界面技术(如JSP、Servlet、Spring MVC)来实现。 5. 最后,关闭与S3的连接,释放资源。 需要注意一些细节事项: - 在处理大文件时,可以使用分块上传和下载来提高性能和效率。 - 要根据文件的MIME类型来决定如何预览文件。可以使用Java文件处理库(如Apache Tika)来确定文件的MIME类型。 - 预览文件时,可能需要进行文件格式转换,以适应不同的预览方式。可以使用相应的Java库来实现文件格式转换。 总之,通过Java S3 SDK,我们可以方便地实现对S3存储桶中文件预览功能。通过合理的设计和使用适当的Java库,可以让预览功能更加灵活、高效和用户友好。 ### 回答2: 在使用Java S3进行文件预览时,可以通过以下步骤实现: 1. 首先,需要将文件上传到Amazon S3存储桶中。可以使用Amazon S3 Java SDK提供的API来实现文件上传功能。通过指定Bucket名称、文件名称和文件内容来上传文件。 2. 一旦文件上传成功,可以通过在Java程序中使用AWS SDK for Java来进行文件预览。可以使用Amazon S3提供的getObject方法来获取文件的内容。 3. 获取到文件内容后,可以根据不同的文件类型对文件进行预览。根据文件的扩展名,可以使用相应的Java库或工具来解析和展示文件内容。 4. 对于文本文件,可以使用Java IO库或Apache Commons IO来读取文件内容,并进行展示。也可以使用第三方库如ANTLR来解析特定格式的文本文件。 5. 对于图像文件,可以使用Java的ImageIO库来读取文件并进行展示。可以通过将图像文件转换为BufferedImage对象,然后使用Java图形库来展示图像。 6. 对于其他类型的文件,可能需要使用特定类型的库来解析和展示。比如,PDF文件可以使用Apache PDFBox库来解析和展示;视频文件可以使用FFmpeg库来解析和展示。 总之,通过Java S3和相关的Java库,可以实现对文件预览功能。根据文件类型的不同,使用相应的库和工具来解析和展示文件内容。 ### 回答3: Java S3(简称Simple Storage Service)是亚马逊网络服务(AWS)提供的一种对象存储服务。它可以存储和检索任意类型的数据文件,并且具有高可用性、可扩展性和安全性。 要在Java中实现文件预览功能,可以使用S3 SDK提供的方法和类来实现。以下是一个基本的实现步骤: 1. 首先,需要在Java项目中导入AWS S3 SDK的依赖项。可以使用Maven或Gradle等构建工具来完成此步骤。 2. 连接到S3存储桶。通过AWS S3 SDK提供的AmazonS3类创建S3客户端,并使用客户端的方法连接到特定的S3存储桶。 3. 获取要预览文件。使用AmazonS3客户端的getObject方法来获取存储桶中的文件对象。需要提供存储桶名称和文件键(key)作为参数。 4. 根据文件类型进行预览。根据文件的类型,可以选择不同的方式进行预览。例如,对于文本文件,可以将其内容读取到Java中并在控制台或用户界面上显示。对于图像或视频文件,可以使用Java的图像或视频处理库来展示文件内容。 5. 完成预览功能后,关闭AmazonS3客户端以释放资源。 需要注意的是,预览文件可能涉及到一些文件类型的转换或解析处理,因此根据需要可能需要使用其他Java库或工具来处理不同的文件类型。 总之,借助Java和AWS S3 SDK,可以轻松实现文件预览功能。通过连接到S3存储桶并获取文件对象,然后根据文件类型选择适当的处理方式,即可完成文件预览操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值