Springboot(九).多文件上傳下載文件(並將url存入數據庫表中)


 

一.   文件上傳

這里我們使用request.getSession().getServletContext().getRealPath("/static")的方式來設置文件的存儲路徑,並存入數據庫中

request.getSession().getServletContext() 獲取的是Servlet容器對象,相當於tomcat容器了。getRealPath("/") 獲取實際路徑,“/”指代項目根目錄,所以代碼返回的是項目在容器中的實際發布運行的根路徑

這里我的文件就保存在了tomcat容器:C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.4580300150688111201.8080\static下

當我們部署到linux的時候,文件就保存在了/tmp/tomcat-docbase.6117940652560190565.8088/static/下

Controller:

/**
 *  多文件上傳接口
 * */
@ResponseBody
@RequestMapping(value = "/fileUpload", produces = "application/json;charset=UTF-8")
public JSONObject fileUpload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws Exception{
    String serverName = "文件上傳";
    VirgoLog.updateStep(CONTROLLER_NAME_DES,serverName);
    List<FileManage> fileManages = fileService.fileUpload(files,request);
    Map<String,Object> resMap = new HashMap<String,Object>();
    //0:操作成功
    resMap.put("code", ErrorCode.ERR_SUCCEED.getErrorCode());
    resMap.put("desc",ErrorCode.ERR_SUCCEED.getErrorMessage());
    resMap.put("fileInfo",fileManages);
    return JSON.parseObject(JSONConvertor.toJSON(resMap));
}

service  文件上傳業務類

/**
     * 文件上傳service
     * @param files
     * @throws Exception
     */
    @Override
    public void fileUpload(@RequestParam("file")MultipartFile[] files, HttpServletRequest request) throws Exception {
        //文件命名
        //保存時的文件名
        for(int i=0;i<files.length;i++) {
            //保存文件到本地文件,並保存路徑到數據庫
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar calendar = Calendar.getInstance();
            String fileName = df.format(calendar.getTime()) + files[i].getOriginalFilename();
            log.log("文件的文件名為:" + fileName);
            //保存文件的絕對路徑
            String filePath = request.getSession().getServletContext().getRealPath("static/");
            log.log("文件的絕對路徑:" + filePath);
            FileManage fileManage = new FileManage();
            try {
                //上傳文件
                FileUtil.uploadFile(files[i].getBytes(), filePath, fileName);
                //保存到數據庫代碼,存入路徑以及文件名稱
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                throw new ZDYException(ErrorCode.ERR_FILE_UPLOAD_FAIL);
            }
        }
            }

  

文件上傳工具類

/**
 * Created by hengyang4 on 2018/11/2.
 */
public class FileUtil {

    //文件上傳工具類服務方法
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception{

        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

}

二.    文件下載

/**
 * 文件下載service
 * @param fileId
 * @throws Exception
 */
@Override
public String downloadFile(String fileId, HttpServletResponse response) throws Exception {
    //這里要根據文件id在數據庫中查詢之前保存的文件信息    FileManage fileManage = fileManageMapper.selectByPrimaryKey(fileId);
    //文件名
    String fileName = fileManage.getFileName();
    //文件的相對路徑
    String path = fileManage.getFilePath();
    InputStream inputStream = new FileInputStream(new File(path + fileName));
    //如果文件不存在
    if(inputStream == null){
        throw new ZDYException(ErrorCode.ERR_NOT_FILE);
    }
    response.setHeader("content-type", "application/octet-stream");
    response.setContentType("application/octet-stream");
    try {
        String name = java.net.URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + name );
    } catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
    }
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
    try {
        os = response.getOutputStream();
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            os.write(buff, 0, buff.length);
            os.flush();
            i = bis.read(buff);
        }
    } catch (FileNotFoundException e1) {
        //e1.getMessage()+"系統找不到指定的文件";
        throw new ZDYException(ErrorCode.ERR_NOT_FILE);
    }catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return "success";

}

  這就是springboot中文件的上傳和下載,很簡單很快捷


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM