SpringBoot入门之六 文件上传

1. 应用场景

2.配置

2.1maven依赖

<!-- Spring Boot web启动器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
 
<!-- jsp -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <!--<scope>provided</scope>-->
</dependency>

2.2 配置文件上传的文件大小限制

 ##jsp视图解析器配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

#文件上传服务
#限制单个文件的最大值
spring.servlet.multipart.max-file-size=200MB
#制上传的多个文件的总大小
spring.servlet.multipart.max-request-size=200MB

3 文件上传的源码

3.1 控制器

@Controller
public class UploadController {

    @Autowired
    private UploadsService uploadsService;

    @GetMapping("/upload")
    public String upload() {
        return "uploads";
    }

    /**
     * 上传
     *
     * @param uploadFile
     * @return
     * @throws IOException
     */
    @RequestMapping(value = {"/do-upload"}, method = RequestMethod.POST)
    public @ResponseBody  Uploads  doUpload(Uploads uploadFile, HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        MultipartFile file = null;
        if (null != multipartRequest.getFile("file")) {
            file = (MultipartFile)multipartRequest.getFile("file");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String filepath = request.getRealPath("") + File.separator + dateFormat.format(new Date()) + File.separator;
            uploadFile = uploadsService.uploadFile(uploadFile, file.getInputStream(), filepath,
                UUID.randomUUID() + file.getOriginalFilename());
        }
        return  uploadFile;
    }
}

本文上传后返回自定义的封装类,故引入fastjson,将自定义改造request请求的结果集
需要引入fastjson

   <dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
	</dependency>
	<dependency>
	    <groupId>com.alibaba</groupId>
	    <artifactId>fastjson</artifactId>
	    <version>1.2.51</version>
	</dependency>

增加启动注册bean

@SpringBootApplication
public class SpringbootTeach6Application {

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

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        // 1、定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2、添加fastjson的配置信息
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        // 3、在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        // 4、将convert添加到converters中
        HttpMessageConverter<?> converter = fastConverter;
        return new HttpMessageConverters(converter);
    }
}

3.2 上传的业务实现类

本文分享上传到应用服务文件目录和上传到阿里云oss两种

@Service
public class UploadsService {

    @Value("${sample.uploads.root-path}")
    private String uploadRootPath;
    @Autowired
    private OssConfig ossConfig;

    public String getUploadRuleForOss(String uploadPath, String fileName) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return ossConfig.getRootPath() + "/" + uploadPath + "/" + dateFormat.format(new Date()) + fileName;
    }
    //上传到阿里云oss
    public String uploadFileToOss(InputStream in, String uploadPath, String fileName)
        throws OSSException, ClientException, FileNotFoundException {
        String relativeFilePath = null;
        // 格式化文件名称和路径
        relativeFilePath = getUploadRuleForOss(uploadPath, fileName);
        return ossConfig.upload(in, relativeFilePath);
    }
    //上传到阿里云oss  并保存上传记录
    public Uploads uploadFileToOss(Uploads uploads, InputStream in, String uploadPath, String fileName) {
        String relativeFilePath = null;
        // 格式化文件名称和路径
        relativeFilePath = getUploadRuleForOss(uploadPath, fileName);
        try {
            if (null == in) {
                throw new NullPointerException("文件流不能为空");
            }
            relativeFilePath = ossConfig.upload(in, relativeFilePath);
            uploads.setRealPath(relativeFilePath);
            uploads.setFilePath(relativeFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            uploads.setStatus("error");
            return uploads;
        }
        uploads.setFileName(fileName);
        uploads.setId(UUID.randomUUID().toString());
        uploads.setCreateTime(new Date());
        // this.insert(uploads);
        return uploads;
    }
    //上传到应用服务器
    public Uploads uploadFile(Uploads uploads, InputStream in, String uploadPath, String fileName)
        throws FileNotFoundException {
        uploads.setRealPath(uploadFile(in, uploadPath, fileName));
        //此处省略保存上传记录的具体实现
        return uploads;
    }
    //上传到应用服务器
    public String uploadFile(InputStream in, String uploadPath, String fileName) throws FileNotFoundException {
        // 格式化文件名称和路径

        File dest = new File(uploadPath + fileName);
        try {
            // 指定上传的文件目录不存在,需要新建
            File parentFile = new File(dest.getParentFile().getAbsolutePath());
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            // 判断文件
            if (!"".equals(fileName.trim())) {
                FileOutputStream os = new FileOutputStream(dest);
                int c;
                byte buffer[] = new byte[1024];
                while ((c = in.read(buffer)) != -1) {
                    for (int i = 0; i < c; i++)
                        os.write(buffer[i]);
                }

            }

            return uploadPath + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传成失败";
        }
    }

}

3.3 上传uploads.jsp文件

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>单文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>
 

3.4 上传

在这里插入图片描述

3.5 上传到阿里云oss

3.5.1 引入阿里云依赖

<dependency>
	<groupId>com.aliyun.oss</groupId>
	<artifactId>aliyun-sdk-oss</artifactId>
	<version>2.4.0</version>
</dependency>

3.5.2 配置阿里云的访问key bukey等

aliyun.oss.access-id=XXX
aliyun.oss.access-key=XXX
aliyun.oss.endpoint=XXX
aliyun.oss.bucket-name=XXX
## 自定义的上传文件目录
aliyun.oss.root-path=temp

以上信息可从购买阿里云oss的服务中获取

3.5.3 增加阿里云属性注册bean

package sample.springboot.teach6.conf;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;

import lombok.Data;

@Data
@Configuration
public class OssConfig {
    /**
     * 阿里云ACCESS_ID
     */
    @Value("${aliyun.oss.access-id}")
    private String ACCESS_ID;
    /**
     * 阿里云ACCESS_KEY
     */
    @Value("${aliyun.oss.access-key}")
    private String ACCESS_KEY;

    /**
     * 阿里云OSS_ENDPOINT 北京Url
     */

    @Value("${aliyun.oss.endpoint}")
    private String OSS_ENDPOINT;

    /**
     * 阿里云BUCKET_NAME OSS
     */
    @Value("${aliyun.oss.bucket-name}")
    private String BUCKET_NAME;

    @Value("${aliyun.oss.root-path}")
    private String rootPath;
    @Autowired
    private OSSClient OSSClient;

 

    @Bean("OSSClient")
    public OSSClient getOssClient() {
        return new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
    }

    public String getUrl(String key) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = OSSClient.generatePresignedUrl(BUCKET_NAME, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    /**
     * 上传
     * 
     * @throws FileNotFoundException
     * @throws ClientException
     * @throws OSSException
     */
    public String upload(String filePath, String fileKey) throws OSSException, ClientException, FileNotFoundException {
        OSSClient.putObject(BUCKET_NAME, fileKey, new FileInputStream(filePath));
        return getUrl(fileKey);
    }

    /**
     * 
     * @return
     */
    public String upload(InputStream in, String fileKey) throws OSSException, ClientException, FileNotFoundException {
        OSSClient.putObject(BUCKET_NAME, fileKey, in);
        return getUrl(fileKey);
    }

}

3.5.4UploadServiece,增加上传阿里云oss方法

@Service
public class UploadsService {

    @Value("${sample.uploads.root-path}")
    private String uploadRootPath;
    @Autowired
    private OssConfig ossConfig;

    public String getUploadRuleForOss(String uploadPath, String fileName) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return ossConfig.getRootPath() + "/" + uploadPath + "/" + dateFormat.format(new Date()) + fileName;
    }

    public String uploadFileToOss(InputStream in, String uploadPath, String fileName)
        throws OSSException, ClientException, FileNotFoundException {
        String relativeFilePath = null;
        // 格式化文件名称和路径
        relativeFilePath = getUploadRuleForOss(uploadPath, fileName);
        return ossConfig.upload(in, relativeFilePath);
    }

    public Uploads uploadFileToOss(Uploads uploads, InputStream in, String uploadPath, String fileName) {
        String relativeFilePath = null;
        // 格式化文件名称和路径
        relativeFilePath = getUploadRuleForOss(uploadPath, fileName);
        try {
            if (null == in) {
                throw new NullPointerException("文件流不能为空");
            }
            relativeFilePath = ossConfig.upload(in, relativeFilePath);
            uploads.setRealPath(relativeFilePath);
            uploads.setFilePath(relativeFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            uploads.setStatus("error");
            return uploads;
        }
        uploads.setFileName(fileName);
        uploads.setId(UUID.randomUUID().toString());
        uploads.setCreateTime(new Date());
        // this.insert(uploads);
        return uploads;
    }

    public Uploads uploadFile(Uploads uploads, InputStream in, String uploadPath, String fileName)
        throws FileNotFoundException {
        uploads.setRealPath(uploadFile(in, uploadPath, fileName));
        return uploads;
    }

    public String uploadFile(InputStream in, String uploadPath, String fileName) throws FileNotFoundException {
        // 格式化文件名称和路径

        File dest = new File(uploadPath + fileName);
        try {
            // 指定上传的文件目录不存在,需要新建
            File parentFile = new File(dest.getParentFile().getAbsolutePath());
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            // 判断文件
            if (!"".equals(fileName.trim())) {
                FileOutputStream os = new FileOutputStream(dest);
                int c;
                byte buffer[] = new byte[1024];
                while ((c = in.read(buffer)) != -1) {
                    for (int i = 0; i < c; i++)
                        os.write(buffer[i]);
                }

            }

            return uploadPath + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传成失败";
        }
    }

}

启动
在这里插入图片描述
上传结果如下
在这里插入图片描述

源码地址

https://gitee.com/xiaolaifeng/sample.springboot/tree/master/springboot-teach6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

浮华落定

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

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

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

打赏作者

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

抵扣说明:

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

余额充值