JAVA 文件的上传下载

一、上传文件

  1、使用 transferTo 上传

@ResponseBody
    @RequestMapping(value = "/file/upload")
    public ResultModel upload(@RequestParam MultipartFile file, HttpServletRequest request) {
        ResultModel resultModel = new ResultModel();
        String fileName = file.getOriginalFilename();
        String newFileName = IdUtil.uuid() + "_" + fileName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateFolder = sdf.format(new Date());

        //文件后缀名
        String fileNameLower = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length()).toLowerCase();//toLowerCase();//小写文件名
        String staticFileType = ".jpg,.png,.txt,.doc,.zip,.mp4";//允许上传的类型格式
        String uploadPath = "/usr/data/upload"; //服务器上传路径

        if(staticFileType.indexOf(fileNameLower) != -1){
            long len = file.getSize(); //上传文件大小
            if(len <= 20971520) {
                if (file.isEmpty()) {
                    return resultModel;
                }
                //上传文件 服务器路径 + 当前日期 例如:201900808
                String fileUploadPath = uploadPath + "/"+dateFolder + "/";
                File f = new File(fileUploadPath);
                if(!f.exists()){
                    f.mkdirs();
                }
                String filePath = fileUploadPath  + newFileName;
                File targetFile = new File(filePath);
                try {
                    //将上传的文件写到服务器上指定的文件。
                    file.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //保存文件路径到数据库中
                fileAttachService.insert(filePath, fileName);
            }else{
                resultModel.setStatus(500);
                resultModel.setStatuMsg("文件大小不能超过20M!"); //文件大小不能超过20M
                return resultModel;
            }
        }else{
            resultModel.setStatus(500);
            resultModel.setStatuMsg("文件后缀名不符合规范!"); //文件后缀名不符合规范
            return resultModel;
        }
        return resultModel;
    }

  2.使用 org.springframework.util.FileCopyUtils.copy()

import org.springframework.util.FileCopyUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


public class UploadFilesController {
    @ResponseBody
    @RequestMapping(value = "/file/upload")
    public ResultModel upload(@RequestParam MultipartFile file, HttpServletRequest request) {
        ResultModel resultModel = new ResultModel();
        String fileName = file.getOriginalFilename();
        String newFileName = IdUtil.uuid() + "_" + fileName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateFolder = sdf.format(new Date());

        //文件后缀名
        String fileNameLower = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length()).toLowerCase();//toLowerCase();//小写文件名
        String staticFileType = ".jpg,.png,.txt,.doc,.zip,.mp4";//允许上传的类型格式
        String uploadPath = "/usr/data/upload"; //服务器上传路径

        if(staticFileType.indexOf(fileNameLower) != -1){
            long len = file.getSize(); //上传文件大小
            if(len <= 20971520) {
                if (file.isEmpty()) {
                    return resultModel;
                }
                //上传文件 服务器路径 + 当前日期 例如:201900808
                String filePath = uploadPath + "/"+dateFolder + "/" ;
               
                File saveFile = new File(filePath,newFileName);
                try {
                    if(!saveFile.exists()){
                        saveFile.createNewFile();
                    }
                    FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(saveFile));
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                //保存文件路径到数据库中
                fileAttachService.insert(filePath, fileName);
            }else{
                resultModel.setStatus(500);
                resultModel.setStatuMsg("文件大小不能超过20M!"); //文件大小不能超过20M
                return resultModel;
            }
        }else{
            resultModel.setStatus(500);
            resultModel.setStatuMsg("文件后缀名不符合规范!"); //文件后缀名不符合规范
            return resultModel;
        }
        return resultModel;
    }
}

二、下载文件

import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.*;
public class UploadFilesController {

    @RequestMapping(value = "/file/download/{fileId}")
    public void download(@PathVariable("fileId") String fileId, HttpServletRequest request, HttpServletResponse response) {
        FileAttach fileAttach = fileAttachService.selectById(fileId);
        File file = new File(fileAttach.getFilePath());

        InputStream in = null;
        OutputStream os = null;
        try {
            //String fileName = URLEncoder.encode(fileAttach.getFileName(), "UTF-8").replaceAll("\+", "%20");
            String fileName = new String(fileAttach.getFileName().getBytes("gb2312"), "ISO8859-1");//解决中文名乱码
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            response.setHeader("Content-Length", ""file.length());//展示下载进度
            in = new FileInputStream(file);
            os = response.getOutputStream();
            IOUtils.copyLarge(in, os);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(os);
        }
    }
}

  

原文地址:https://www.cnblogs.com/bert227/p/11364551.html