java上传下载通用方法总结之file.transferTo(targetFile)(二)

java上传下载通用方法总结 之file.transferTo(targetFile)(二)

最近新捕获文件上传、下载、预览的方法。特地总结,方便调用。
先看公共类的公共方法:

package com.sinux.cc.fileuploadanddownload.newfileio;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileIOUtil {
    private static String prefix;
    static {
    /**
    *它 是项目所在地址:这里的上传下载预览,都是要全路径跟(一)中的方法不一样
    *E:\2020-in-beijing\java8\mycodeinbeijing
    **/
        prefix = System.getProperty("user.dir");
    }
    //下载
    public static ResponseEntity downloadFile(String path) {
      
        path = prefix + path;
        File f = new File(path);
        System.out.println(f);
        if (f.exists() && f.isFile()) {
            String fileName = f.getName();
            try {
                String contentType = Files.probeContentType(Paths.get(path));
                Resource resource = new UrlResource(Paths.get(path).toUri());
                if (StringUtils.isEmpty(contentType)) {
                    contentType = "application/" + fileName.substring(fileName.lastIndexOf(".") + 1);
                }
                // fileName = getFileName(fileName);
                ResponseEntity<Resource> body = ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).
                        header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" +
                                new String(fileName.getBytes("UTF-8"), "ISO8859-1")).
                        body(resource);

                return body;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    //预览
    public static ResponseEntity previewFile(String path) {
        path = prefix + path;
        if (!StringUtils.isEmpty(path)) {
            File file = new File(path);
            if (file.exists()) {
                String fileName = file.getName();
                try {
                    String contentType = Files.probeContentType(Paths.get(path));
                    Resource resource = new UrlResource(Paths.get(path).toUri());
                    if (StringUtils.isEmpty(contentType)) {
                    if(fileName.endsWith(".svg")){
                    contentType = "image/svg+xml";
                    }else{
                     contentType = "application/" + fileName.substring(fileName.lastIndexOf(".") + 1);
                    } 
                    }
                    return ResponseEntity.ok().
                            contentType(MediaType.parseMediaType(contentType)).
                            header(HttpHeaders.CONTENT_DISPOSITION, "inline;filename" +
                                    URLEncoder.encode(fileName, "UTF-8")).body(resource);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //上传
    public static String uploadFile(MultipartFile file, String uploadpath) {
        if (file != null) {
            String fileName = file.getOriginalFilename();
            if (!StringUtils.isEmpty(fileName)) {
                String folderpath = prefix + uploadpath;
                File f = new File(folderpath);
                if (!f.exists()) {
                    f.mkdirs();
                }
                File targetFile = new File(f, fileName);
                if (targetFile.exists()) {
                    targetFile.delete();
                }

                try {
                    file.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return uploadpath + fileName;
            }
        }
        return null;
    }
}

调用的地方:

package com.sinux.cc.fileuploadanddownload.controller;

import com.sinux.cc.fileuploadanddownload.FileDownload;
import com.sinux.cc.fileuploadanddownload.FileUpload;
import com.sinux.cc.fileuploadanddownload.newfileio.FileIOUtil;
import com.sinux.cc.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@Api(tags = "文件上传下载操作")
@RequestMapping("/fileoperate")
@Slf4j
public class FileOperateController {
	/**
	*在yml中配置的:
	*fileiodir:
     * upanddown: "/files/0715file/"
	**/
    @Value("${fileiodir.upanddown}")
    private String uploadpath;

 
    @GetMapping("/jnf")
    @ApiOperation(value = "使用java.nio.file下载文件")
    public ResponseEntity testResponseEntity(String path){
        log.info("path==============="+path);
        ResponseEntity<InputStreamResource> inputStreamResourceResponseEntity = null;
        try {
            inputStreamResourceResponseEntity =
                    FileIOUtil.downloadFile(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStreamResourceResponseEntity;
    }

    @PostMapping("/uploadfiles")
    @ApiOperation(value = "上传文件")
    public R uploadFiles(MultipartFile file){
        String s = FileIOUtil.uploadFile(file,uploadpath);
        return R.ok("").put("path",s);
    }
    
    @PostMapping("/preview")
    @ApiOperation(value = "预览图片")
    public ResponseEntity preView(String path){
        ResponseEntity responseEntity = FileIOUtil.previewFile(path);
        return responseEntity;
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神雕大侠mu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值