springboot 文件上传+异常处理+错误页面跳转

1.项目结构搭建

2. 相关依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--thymeleaf支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

3.静态资源文件准备

static/ upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件到服务器</title>
</head>
<body>
<!--method=post enctype=multipart/form-data-->
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFile" value="请选择文件">
    <input type="submit" value="上传">
</form>
</body>
</html>

static/ upload2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>多文件上传</title>
</head>
<body>
<form action="/upload2" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFiles" value="请选择文件" multiple="multiple">
    <input type="submit" value="上传">
</form>
</body>
</html>

templates/ myError.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    welcome to myError page
</body>
</html>

resources/ 401.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>welcome to error 401 page</h1>
</body>
</html>

 402.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>welcome to error 402 page</h1>
</body>
</html>

403.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>welcome to error 403 page</h1>
</body>
</html>

404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>welcome to error 404 page</h1>
</body>
</html>

4.springboot配置相关

##上传文件请求最大值
#spring.servlet.multipart.max-request-size=100MB
##上传单个文件的最大值
#spring.servlet.multipart.max-file-size = 10MB

#url输入这样的表达式进行访问,默认是/**(一层目录任意匹配,/**/**效果还是/**)
#spring.mvc.static-path-pattern=/uploadFile/**
spring.mvc.static-path-pattern=/**
#spring.mvc.static-path-pattern=/**/**

#静态资源可访问位置(优先级从左到右递减),第一个/表示当前resources/目录位置
#spring.resources.static-locations=classpath:/uploadFile/
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
classpath:/static/,classpath:/public/,classpath:/uploadFile/,classpath:/

#只能设置单个
#spring.thymeleaf.prefix=classpath:/
spring.thymeleaf.prefix=classpath:/templates/

5.单文件上传

package com.example.demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * 文件上传实现步骤
 * 1.upload.html选择文件
 * 2.upload.html上传文件
 * 3.UploadController通过设置@RestController注解,来接收网页的请求
 * 4.通过MultipartFile和HttpServletRequest拿到上传的文件和请求信息
 * 5.创建存储文件的目录
 * 6.通过uploadFile.transferTo(fileServer); 把上传的文件存储到服务器
 * 7.返回一个可以访问文件的网址
 */
@RestController
public class UploadController {

    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request){
        File dir = new File("D:/idea working/springboot study/springboot-single-file-upload/uploadFile/");
        File dir = new File("src/main/resources/uploadFile/");//src前面不要带上斜杠
        System.out.println(dir);
        if (!dir.isDirectory()) {//文件目录不存在,就创建一个
            dir.mkdirs();
        }
        try {
            String filename = uploadFile.getOriginalFilename();//获得上传时的文件名
//            File fileServer = new File(dir, filename);
            File fileServer = new File(dir.getAbsolutePath(),filename);
            System.out.println("file文件真实路径:" + fileServer.getAbsolutePath());
            uploadFile.transferTo(fileServer);//把上传的文件存储到服务器
            //协议名称+网站域名+请求端口+上传文件名
            String filePath = request.getScheme() + "://"
                    + request.getServerName() + ":"
                    + request.getServerPort() + "/uploadFile/"
                    + filename;
            return filePath;//返回可供访问的网络路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
}

6.多文件上传

package com.example.demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * 多文件上传
 */
@RestController
public class UploadController2 {
    @PostMapping("/upload2")
    public String uploads(MultipartFile[] uploadFiles, HttpServletRequest request) {
        if (uploadFiles == null || uploadFiles.length < 1) {
            return "文件不能为空";
        }

        File dir = new File("src/main/resources/uploadFile/");//src前面不要带上斜杠
        if (!dir.isDirectory()) {//文件目录不存在,就创建一个
            dir.mkdirs();
        }
        try {
            String filePathS = "";
            //遍历文件数组,一个个上传
            for (int i = 0; i < uploadFiles.length; i++) {
                MultipartFile uploadFile = uploadFiles[i];
                String filename = uploadFile.getOriginalFilename();//获得上传时的文件名
                File fileServer = new File(dir.getAbsolutePath(), filename);
                System.out.println("file文件真实路径:" + fileServer.getAbsolutePath());
                uploadFile.transferTo(fileServer);//把上传的文件存储到服务器
                String filePath = request.getScheme() + "://" +
                        request.getServerName() + ":"
                        + request.getServerPort()
                        + "/uploadFile/" + filename;
                filePathS = filePathS + "\n" + filePath;
            }
            return filePathS;//返回可供访问的网络路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
}

7.异常处理

ErrorController

package com.example.demo.dealExceptions;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义异常处理
 */
@RestController
public class ErrorController {
    @GetMapping("/errorTest")
    public void error(){
        System.out.println("测试全局异常");
        int a=5/0;
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public void testException() throws UserNotExistException {
        System.out.println("测试局部异常");
        throw new UserNotExistException();
    }

    @ExceptionHandler(UserNotExistException.class)
    public Map<String,Object> exceptionHandler(Exception e) {
        System.out.println(e.getMessage());
        Map<String,Object> map = new HashMap<>();
        map.put("code","notExist");
        map.put("message","用户不存在");
        return map;
    }
}

MyExceptionHandler

package com.example.demo.dealExceptions;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * 异常处理器:捕获全局异常
 */
@ControllerAdvice //controller增强器,用来捕获controller里的异常
public class MyExceptionHandler {
    @ResponseBody //返回错误信息
    @ResponseStatus //返回错误状态
    @ExceptionHandler(Exception.class) //捕获范围
    public String handlerMethodArgumentException(Exception e){
        System.out.println(e.getClass().getName());
        if(e instanceof MaxUploadSizeExceededException){
            return "文件过大";
        }
        return "错误信息:"+e.getMessage();
    }
}

UploadController

package com.example.demo.dealExceptions;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * 文件上传实现步骤
 * 1.upload.html选择文件
 * 2.upload.html上传文件
 * 3.UploadController通过设置@RestController注解,来接收网页的请求
 * 4.通过MultipartFile和HttpServletRequest拿到上传的文件和请求信息
 * 5.创建存储文件的目录
 * 6.通过uploadFile.transferTo(fileServer); 把上传的文件存储到服务器
 * 7.返回一个可以访问文件的网址
 */
@Controller("wxd")
@ResponseBody
public class UploadController {

    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request){
        System.out.println("[==package com.example.demo.dealExceptions==]");
        File dir = new File("D:/idea working/springboot study/springboot-single-file-upload/uploadFile/");
        File dir = new File("src/main/resources/uploadFile/");//src前面不要带上斜杠
        System.out.println(dir);
        if (!dir.isDirectory()) {//文件目录不存在,就创建一个
            dir.mkdirs();
        }
        try {
            String filename = uploadFile.getOriginalFilename();//获得上传时的文件名
//            File fileServer = new File(dir, filename);
            File fileServer = new File(dir.getAbsolutePath(),filename);
            System.out.println("file文件真实路径:" + fileServer.getAbsolutePath());
            uploadFile.transferTo(fileServer);//把上传的文件存储到服务器
            //协议名称+网站域名+请求端口+上传文件名
            String filePath = request.getScheme() + "://"
                    + request.getServerName() + ":"
                    + request.getServerPort() + "/uploadFile/"
                    + filename;
            return filePath;//返回可供访问的网络路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
}
UserNotExistException
package com.example.demo.dealExceptions;

public class UserNotExistException extends Throwable {
}

8.错误跳转处理

MyErrorController
package com.example.demo.errorPage;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyErrorController implements ErrorController {

    private static final String PATH = "/error";

    //url请求时404,,springboot会默认处理,进入该方法
    @RequestMapping(value = PATH)
    public String error() {
        System.out.println("11");
//        return "401";//
        return "myError";//
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

    //Controller间跳转
    @RequestMapping("/testRedirect")
    public String testRedirect() {
        System.out.println("开始重定向");
        return "redirect:"+PATH;
    }
}
PageController
package com.example.demo.errorPage;


import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义异常处理
 */
//@Controller
//public class PageController implements ErrorController {
//
//    @RequestMapping("/error")
//    public String handleError(HttpServletRequest request) {
//        System.out.println("[PageController]");
//        //获取statusCode:401,404,500
//        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
//        System.out.println(statusCode==null?"":statusCode);
//        switch (statusCode) {
//            case 400:
//                return "400";
//            case 401:
//                return "401";
//            case 500:
//                return "402";
//            default:
//                return "403";
//        }
//    }
//
//    @Override
//    public String getErrorPath() {
//        return null;
//    }
//
//    @RequestMapping("/test")
//    public String test(){
//        System.out.println("go");
        return "401.html";
//        return "403";//有thymeleaf支持,可省略后缀
//    }
//
//}

9.启动

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
//@ComponentScan(basePackages = {"com.example.demo.dealExceptions","com.example.demo.errorPage"})
@ComponentScan(basePackages = {"com.example.demo.errorPage"})
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值