Spring Boot MVC 单张图片和多张图片上传 和通用文件下载

复制代码
@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);
    }
}
复制代码

 

posted @   LowKeyC  阅读(258)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
有志者事竟成破釜沉舟百二秦关终属楚苦心人,天不负,卧薪尝胆,三千越甲可吞吴
点击右上角即可分享
微信分享提示