Spring Boot 整合之文件上传与下载(本地及网络url下载)

41 篇文章 0 订阅
25 篇文章 3 订阅

1.导入依赖

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

2.编写封装类 返回信息

public class FileInfo {

    private String path;

    public FileInfo(String path) {
        this.path = path;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

}

3.编写controller 实现文件上传与下载

3.1创建

@RestController
@RequestMapping("/file")
public class FileController {


    /**
     * 上传图片
     * @param file
     * @param req
     * @return
     * @throws Exception
     */
    @PostMapping
    public FileInfo upload(MultipartFile file,HttpServletRequest req) throws Exception {

        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());//原图片名
        System.out.println(file.getSize());//大小
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        //图片名
        String fileName = URLEncoder.encode(file.getOriginalFilename(), "UTF-8");
        fileName=sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.'));
        //路径
        String path=req.getSession().getServletContext().getRealPath("/")+ "upload\\";
        File localFile = new File(path, fileName);

        file.transferTo(localFile);
        //返回json格式
        return new FileInfo(localFile.getAbsolutePath());
    }

    /**
     * 下载图片
     * @param id
     * @param request
     * @param response
     */
    @GetMapping("/{id}")//id为要下载的图片名:123.jsp
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        String path=request.getSession().getServletContext().getRealPath("/")+ "upload\\";

         //根据url获取输入流
        //URL url = new URL(zipUrl);
        //HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        //conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        //conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        //InputStream inputStream = conn.getInputStream();
          //-------------------------------------------

          //下载
        try (InputStream inputStream = new FileInputStream(new File(path, id ));
             OutputStream outputStream = response.getOutputStream();) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + id);

            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

如果路径异常,用以下方法获取路径:

    /**
     * 获取图片上传路径
     * @return
     * @throws Exception
     */
    public static String getPath() throws Exception {
        //路径
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) {
            path = new File("");
        }
//如果上传目录为/static/images/upload/,则可以如下获取
        File upload = new File(path.getAbsolutePath(), "static/upload/");

        if (!upload.exists()) {
            upload.mkdirs();
//            System.out.println(upload.getAbsolutePath());
            //在开发测试模式时,得到地址为:{项目跟目录}/target/static/images/upload/
            //在打成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/
        }
        return upload.getAbsolutePath();
    }

3.2@RestController和@Controller区别

@RestController注解相当于@ResponseBody + @Controller合在一起的作用。

1) 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。

转json请看https://blog.csdn.net/qq_40369944/article/details/83898752

2) 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
    如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

4.测试

4.1上传

4.1.1html:

<form action="/file" method="post"  enctype="multipart/form-data" >
        <input type="file" name="file">
        <input type="submit" value="ok">
    </form>

4.1.2页面:

4.1.3结果:

4.2下载

我就直接根据项目中的图片名下载

get方式    地址:

浏览器下载:

 

 

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot整合Spring Security可以实现对应用程序的安全认证和授权功能。下面是一个简单的示例: 1. 添加Spring Security依赖:在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 创建一个配置类:创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure方法来配置安全策略。以下是一个示例: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } } ``` 上述示例中的configure方法配置了对应用程序路径的访问权限,configureGlobal方法配置了一个简单的内存用户认证。 3. 创建登录页面:在src/main/resources/static目录下创建一个login.html文件作为登录页面。 4. 运行应用程序:启动Spring Boot应用程序,并访问相应的URL(例如,http://localhost:8080/login)试图访问受保护的资源。系统将会自动重定向到登录页面,输入用户名和密码后即可访问受保护的资源。 上述步骤是一个简单的Spring Boot整合Spring Security的示例。你可以根据自己的需求进行更复杂的配置和定制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云下的你

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值