文件上传下载小工具类


```import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriUtils;

import java.io.File;
import java.util.Date;

/**
 * @author Mr.Li
 */
public class DownloadUtil {


    public static ResponseEntity<FileSystemResource> downloadFile(File file,String fileName) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + UriUtils.encode(fileName, "UTF-8"));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));

    }
}
@RequestMapping(value = "/xxx")
    public ResponseEntity<FileSystemResource> downloadManual(@RequestParam(value = "fileName",required = false)String fileName) throws IOException{
        String fileUrl = "xxx";
        File file = new File(fileUrl);
        fileName = fileName+"."+fileUrl.split("\\.")[1];
        return DownloadUtil.downloadFile(file,fileName);
    }


## 标题
上传图片工具类
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class FileTools {

    /**
     * 上传图片,并返回图片路径
     */
    public static Map<String, Object> upload(MultipartFile file, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        //获得当前操作系统的名称
        String os = System.getProperty("os.name");
        //过滤合法的文件类型
        String name = file.getOriginalFilename(); //上传文件的真实名称
        //获取后缀名
        String expandedName = name.substring(name.lastIndexOf(".") + 1);
        //获取真实路径
        String path = "";
        //创建新目录
        /*String uri = File.separator + getNowDateStr(File.separator);
        File dir = new File("/xxx/xxx/" + uri);*/
        //在win系统下与linux以及mac下生成的路径
        if (os.toLowerCase().startsWith("win")) {

            path = System.getProperty("user.dir")+"\\xxx\\xx\\xx\\xxx\\xxx\\ixxx\\xxx\\";
        } else {  //linux 和mac
            path =  request.getServletContext().getRealPath("/");
            path = File.separator+path.split("/")[1]+File.separator+"image"+File.separator;
        }
        //创建新文件
        String fileName = getUniqueFileName()+ "."+expandedName;
        File tempFile=new File(path,fileName);
        try {
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            if (tempFile.exists()) {
                tempFile.delete();
            }
            tempFile.createNewFile();
            file.transferTo(tempFile);

        } catch (IOException e) {
            e.printStackTrace();
        }
        String path1 = tempFile.getPath();
        map.put("url",path+fileName);
        return map;
    }

    /**
     * 获取当前日期字符串
     *
     * @param separator
     * @return
     */
    public static String getNowDateStr(String separator) {
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        //month 记得加一(因为默认从0开始计数)
        int month = now.get(Calendar.MONTH) + 1;
        int day = now.get(Calendar.DATE);

        return year + separator + month + separator + day;
    }

    //生成唯一的文件名
    public static String getUniqueFileName() {
        String str = UUID.randomUUID().toString();
        return str.replace("-", "");
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

江湖人,江湖事

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

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

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

打赏作者

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

抵扣说明:

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

余额充值