SpringBoot 文件或图片上传与下载功能的实现

导入依赖(pom.xml)

   <!-- 上传下载需要设计到的jar包 -->
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.6</version>
  </dependency>
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
  </dependency>
  <!--servlet-api导入高版本的-->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
  </dependency>
  <!-- 图片处理类 -->
  <dependency>
   <groupId>net.coobird</groupId>
   <artifactId>thumbnailator</artifactId>
   <version>0.4.8</version>
  </dependency>

全局配置 application.properties

# 上传文件大小
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB

创建 WebMvcConfig 配置类  静态资源映射

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

 @Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
  ApplicationHome h = new ApplicationHome(getClass());
  File jarF = h.getSource();
  String dirPath = jarF.getParentFile().toString()+"/upload/";

  String os = System.getProperty("os.name");

  if (os.toLowerCase().startsWith("win")) { //如果是Windows系统
   registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
  } else {
   registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
  }
 }

}

文件或图片上传

控制层

// 上传文件
 @ResponseBody
 @RequestMapping("/upload")
 public String fileUpload(@RequestParam("files") MultipartFile files) throws IOException {
//  // win系统 上传路径保存设置
//  // 获取项目路径
//  File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
//  // 绝对路径=项目路径+自定义路径
//  File pathFile = new File(projectPath.getAbsolutePath(), "static/upload/");
//  if (!pathFile.exists()) {
//   pathFile.mkdirs();
//  }
//  //上传文件地址
//  UUID uuid = UUID.randomUUID();
//  File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
//  files.transferTo(serverFile);
//
//  String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");
//
//  return imgPath;

  // Linux服务器 上传路径保存设置
  // 项目路径 /home/www/
  File pathFile = new File("/home/www/upload/");
  if (!pathFile.exists()) {
   pathFile.mkdirs();
  }
  //上传文件地址
  UUID uuid = UUID.randomUUID();
  File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
  files.transferTo(serverFile);

  String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");

  return imgPath;
 }

HTML页面

Ajax 无刷新上传

<form action="" class="layui-form" enctype="multipart/form-data" method="post">
  <input type="hidden" name="blogImg" id="imgPath" value="">
  <div class="form-group">
    <label>图片上传</label>
    <input type='file' style='margin: 5px;' name='files' required><br>
    <button type="button" class="layui-btn" id="img_upload">上传图片</button>
  </div>
  <input type="submit">
</form>

JS

//普通图片上传
  $('#img_upload').click(function () {
   var formData = new FormData();
   //获取选择的文件
   $.each($('input[name="files"]'),function (index,item) {
    formData.append("files",item.files[0])
   });

   //发送异步请求
   $.ajax({
    method:'post',
    url: '[[@{/user/upload}]]', // 文件上传接口
    data:formData,
    processData: false,
    contentType:false,
    success:function (data) {
     //成功返回触发的方法
     $('#imgPath').val(data);
     alert("上传成功");
    },
    //请求失败触发的方法
    error:function () {
     alert("上传失败");
    }
   });
  });

文件或图片下载

控制层

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
 //要下载的图片地址
 String path = request.getServletContext().getRealPath("/upload");
 String fileName = "基础语法.jpg";

 //1、设置response 响应头
 response.reset(); //设置页面不缓存,清空buffer
 response.setCharacterEncoding("UTF-8"); //字符编码
 response.setContentType("multipart/form-data"); //二进制传输数据
 //设置响应头
 response.setHeader("Content-Disposition",
   "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

 File file = new File(path,fileName);
 //2、 读取文件--输入流
 InputStream input=new FileInputStream(file);
 //3、 写出文件--输出流
 OutputStream out = response.getOutputStream();

 byte[] buff =new byte[1024];
 int index=0;
 //4、执行 写出操作
 while((index= input.read(buff))!= -1){
  out.write(buff, 0, index);
  out.flush();
 }
 out.close();
 input.close();
 return null;
}

HTML页面

<a href="/download" rel="external nofollow" >点击下载</a>

SpringBoot 文件或图片上传与下载就可以了

到此这篇关于SpringBoot 文件或图片上传与下载功能的实现的文章就介绍到这了,更多相关SpringBoot 文件上传与下载内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringBoot实现单文件与多文件上传功能

    目录 1.单文件上传 2.多文件上传 1.单文件上传 首先创建一个Spring Boot项目,并添加spring-boot-starter-web依赖 然后创建一个upload.jsp文件,做一个简单的文件上传页面,具体代码如下: <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head>     <title>Titl

  • jquery+springboot实现文件上传功能

    本文实例为大家分享了jquery+springboot实现文件上传功能的具体代码,供大家参考,具体内容如下 前端 <!DOCTYPE html> <html lang="zh"> <head> <title></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-w

  • springboot+thymeleaf 文件上传功能的实现代码

    pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifa

  • SpringBoot实现文件上传功能

    经典的文件上传 服务器处理上传文件一般都是先在请求中读取文件信息,然后改变名称保存在服务器的临时路径下,最后保存到服务器磁盘中.本次以thymeleaf搭建demo,因此需要引入thymeleaf依赖库. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <versio

  • SpringBoot 文件或图片上传与下载功能的实现

    导入依赖(pom.xml) <!-- 上传下载需要设计到的jar包 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-fileu

  • WebApi2 文件图片上传与下载功能

    Asp.Net Framework webapi2 文件上传与下载 前端界面采用Ajax的方式执行 一.项目结构 1.App_Start配置了跨域访问,以免请求时候因跨域问题不能提交.具体的跨域配置方式如下,了解的朋友请自行略过. 跨域配置:NewGet安装dll Microsofg.AspNet.Cors 然后在App_Start 文件夹下的WebApiConfig.cs中写入跨域配置代码. public static class WebApiConfig { public static vo

  • Django 实现图片上传和下载功能

    原生上传图片方式 #新建工程 python manage.py startapp test30 #修改 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stu'

  • spring boot实现图片上传和下载功能

    这篇博客简单介绍下spring boot下图片上传和下载,已经遇到的问题.首先需要创建一个spring boot项目. 1.核心的controller代码 package com.qwrt.station.websocket.controller; import com.alibaba.fastjson.JSONObject; import com.qwrt.station.common.util.JsonUtil; import org.slf4j.Logger; import org.slf

  • 详解PHP素材图片上传、下载功能

    这里的下载是生成 zip 包进行下载,所以需要 PHP 的ZipArchive ()类,使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释.并且不包括 oss 之类的三方 上传 上传就很简单了,PHP 自带的 move_uploaded_file()函数就可以使用我们简单的文件上传了. 我们只需要把文件的路径存到数据库方便我们下载或展示时使用就 OK了. 这里需要注意上传的路径和文件名尽量不要包括中文. 下载 下载文件我们需要临时生成一个服务器的 zip 包,

  • SpringBoot限制文件或图片上传大小的两种配置方法

    今天做图片上传时候,报了如下错:服务运行异常,Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted

  • SpringBoot+微信小程序实现文件上传与下载功能详解

    目录 1.文件上传 1.1 后端部分 1.2 小程序前端部分 1.3 实现效果 2.文件下载 2.1 后端部分 2.2 小程序前端部分 2.3 实现效果 1.文件上传 1.1 后端部分 1.1.1 引入Apache Commons FIleUpload组件依赖 <!--文件上传与下载相关的依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fil

  • SpringBoot实现文件上传与下载功能的示例代码

    目录 Spring Boot文件上传与下载 举例说明 1.引入Apache Commons FileUpload组件依赖 2.设置上传文件大小限制 3.创建选择文件视图页面 4.创建控制器 5.创建文件下载视图页面 6.运行 Spring Boot文件上传与下载 在实际的Web应用开发中,为了成功上传文件,必须将表单的method设置为post,并将enctype设置为multipart/form-data.只有这种设置,浏览器才能将所选文件的二进制数据发送给服务器. 从Servlet 3.0开

  • SpringBoot文件上传与下载功能实现详解

    目录 前言 1.引入Apache Commons FileUpload组件依赖 2.设置上传文件大小限制 3.创建选择文件视图页面 4.创建控制器 5.创建文件下载视图页面 前言 文件上传与下载是Web应用开发中常用的功能之一,在实际的Web应用开发中,为了成功上传文件,必须将表单的method设置为post,并将enctype设置为multipart/form-data 只有这样设置,浏览器才能将所选文件的二进制数据发送给服务器 从Servlet3.0开始,就提供了处理文件上传的方法,但这种文

  • SpringBoot+Vue3实现文件的上传和下载功能

    目录 前言 上传前端页面 上传后端代码 下载后端代码 总结 参考文献 前言 上传文件和下载文件是我们平时经常用到的功能,接下来就让我们用SpringBoot,Vue3和ElementPlus组件实现文件的上传和下载功能吧~ 上传前端页面 前端页面我们可以使用ElementPlus框架的el-upload组件完成上传,主要的参数解释如下: action属性:指定请求的url onsuccess属性: 请求成功后的回调函数 我们可以使用axios向后端发起get请求,然后后端返回文件保存的位置 表单

随机推荐