Spring Boot MVC 單張圖片和多張圖片上傳 和通用檔案下載

LowKeyC發表於2021-04-03
@Autowired
private ServerConfig serverConfig;

/**
 * 通用下載請求
 *
 * @param fileName 檔名稱
 * @param delete 是否刪除
 */
@ApiOperation("通用下載請求")
@GetMapping("/download")
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
{
    try
    {
        if (!FileUtils.checkAllowDownload(fileName))
        {
            throw new Exception(StringUtils.format("檔名稱({})非法,不允許下載。 ", fileName));
        }
        String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
        String filePath = RuoYiConfig.getDownloadPath() + fileName;

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, realFileName);
        FileUtils.writeBytes(filePath, response.getOutputStream());
        if (delete)
        {
            FileUtils.deleteFile(filePath);
        }
    }
    catch (Exception e)
    {
        log.error("下載檔案失敗", e);
    }
}

/**
 * 通用上傳請求
 */
@ApiOperation("通用上傳請求")
@PostMapping("/upload")
public AjaxResult uploadFile(MultipartFile file) throws Exception
{
    try
    {
        // 上傳檔案路徑
        String filePath = RuoYiConfig.getUploadPath();
        // 上傳並返回新檔名稱
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileName", fileName);
        ajax.put("url", url);
        return ajax;
    }
    catch (Exception e)
    {
        return AjaxResult.error(e.getMessage());
    }
}


@RequestMapping("xxx")
public String fileImgSave(@RequestParam("filename") MultipartFile[] files, HttpServletRequest request){
   //儲存檔案的路徑
    String realPath =RuoYiConfig.getUploadPath(); //request.getSession().getServletContext().getRealPath("/imgssss");
    File path = new File(realPath);
    if(!path.exists()){
        path.mkdirs();
    }
    //判斷file陣列不能為空並且長度大於0
    if(files != null && files.length > 0){
        //迴圈獲取file陣列中得檔案
        for(int i = 0;i < files.length;i++){
            MultipartFile file = files[i];
            //儲存檔案
            if (!file.isEmpty()){
                try {
                    //轉存檔案 file.getOriginalFilename();檔案原名稱包括字尾名
                    file.transferTo(new File(realPath+"/img"+i+".png"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    return "ok";
}


/**
 * 通用上傳請求
 */
@ApiOperation("通用上傳請求")
@PostMapping("/uploadList")
public AjaxResult uploadFileList(MultipartFile [] file,HttpServletRequest request) throws Exception
{

    List<String> fileNameList=new ArrayList<>();

    List<String> urllList=new ArrayList<>();

    try {
        // 上傳檔案路徑qinm
        String filePath = RuoYiConfig.getUploadPath();

        //判斷file陣列不能為空並且長度大於0
        if (file != null && file.length > 0) {

            for (int i = 0; i < file.length; i++)
            {
                {
                    MultipartFile files = file[i];

                    // 上傳並返回新檔名稱
                    String fileName = FileUploadUtils.upload(filePath, files);
                    String url = serverConfig.getUrl() + fileName;

                    fileNameList.add(fileName);
                    urllList.add(url);
                }
            }

            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileNameList);
            ajax.put("url", urllList);
            return ajax;
        }
        else
        {
            return AjaxResult.error("請選擇上傳的圖片");

        }
    }
    catch (Exception e)
    {
        return AjaxResult.error(e.getMessage());
    }
}

/**
 * 本地資源通用下載
 */
@ApiOperation("本地資源通用下載")
@GetMapping("/download/resource")
public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
        throws Exception
{
    try
    {
        if (!FileUtils.checkAllowDownload(resource))
        {
            throw new Exception(StringUtils.format("資原始檔({})非法,不允許下載。 ", resource));
        }
        // 本地資源路徑
        String localPath = RuoYiConfig.getProfile();
        // 資料庫資源地址
        String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
        // 下載名稱
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, downloadName);
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }
    catch (Exception e)
    {
        log.error("下載檔案失敗", e);
    }
}

 

相關文章