Spring Boot 2.X 学习日记——搞定文件上传

前言

文件上传是web应用中,常见的操作之一。在Spring Boot中,我们可以很容易的完成这个功能。

具体编码

本节主要是基于MVC结构来讲述的,所以我们需要引入视图层的相关框架。

添加依赖

    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-thymeleaf'

准备

  1. application.yml中添加上传相关配置

    upload:
      path: ./upload/
    
  2. 新建upload文件夹,用于存放上传文件

编码

UploadController.java

package com.boot.demo.controller;

import com.boot.demo.service.UploadService;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @RequestMapping("index")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/upload/index");
        return mv;
    }

    @RequestMapping("uploadFile")
    @ResponseBody
    public Map uploadFile(@RequestParam(name = "file") MultipartFile[] file){
        Map<String,String> result = new HashMap<>();
        try {
            uploadService.uploadFile(file);
            result.put("code","200");
            result.put("msg","上传成功");
        } catch (Exception e){
            result.put("code","500");
            result.put("msg","上传失败");
        }
        return result;
    }

    @RequestMapping("uploadBase64File")
    @ResponseBody
    public Map uploadFile(@RequestParam String baseStr){
        Map<String,String> result = new HashMap<>();
        try {
            uploadService.uploadBase64File(baseStr);
            result.put("code","200");
            result.put("msg","上传成功");
        } catch (Exception e){
            result.put("code","500");
            result.put("msg","上传失败");
        }
        return result;
    }
}

UploadService.java

package com.boot.demo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Service
public class UploadService {

    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);

    @Value("${upload.path}")
    private String uploadPath;

    public void uploadFile(MultipartFile...files){
        for(MultipartFile file : files){
            try {
                uploadFile(file.getInputStream(), file.getOriginalFilename());
            } catch (IOException e){
                logger.error("上传失败...",e.getMessage(),e);
                throw new RuntimeException();
            }
        }

    }

    public void uploadBase64File(String baseStr){
        String[] strs = baseStr.split("base64,");
        byte[] buf = Base64Utils.decodeFromString(strs.length > 1 ? strs[1] : strs[0]);
        ByteArrayInputStream bis = new ByteArrayInputStream(buf);
        try {
            uploadFile(bis, "temp.png");
        } catch (IOException e){
            logger.error("上传失败...",e.getMessage(),e);
            throw new RuntimeException();
        }
    }

    private void uploadFile(InputStream inputStream,String name) throws IOException{
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(uploadPath + name);
        } catch (FileNotFoundException ex) {
            File file = new File(uploadPath + name);
            file.createNewFile();
            fos = new FileOutputStream(file);
        }

        try {
            FileCopyUtils.copy(inputStream,fos);
        } finally {
            inputStream.close();
            fos.flush();
            fos.close();
        }

    }
}

BootApplication.java

package com.boot.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *	上传文件
 *	Author : Ivan
 **/
@SpringBootApplication
public class BootApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class,args);
    }
}

测试

接着,就可以自行启动项目,访问http://localhost:8080/upload/index进行单文件,多文件,Base64文件上传的测试了。

Base64测试

Base64文件,读者们可以访问Base64转换工具,将文件上传至该网站后,再将生成的字符串粘贴过来,就可以测试了。

全文代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值