首页 > 其他分享 >springboot文件上传下载到本机服务器上

springboot文件上传下载到本机服务器上

时间:2024-05-14 09:43:41浏览次数:15  
标签:String 上传下载 class file filename 本机 public storageService springboot

这次的文件上传下载仅指的是本机的服务器,不指第三方文件存储系统!!!

1.在pom中加入以下依赖,如已经加入,请忽略

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

 2.创建controller


@Controller
@RequestMapping("/fileUpload")
public class FileUploadController {

    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/form")
    public String listUploadedFiles(Model model) throws IOException {

        model.addAttribute("files", storageService.loadAll().map(
                        path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
                                "serveFile", path.getFileName().toString()).build().toUri().toString())
                .collect(Collectors.toList()));

        return "uploadForm";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = storageService.loadAsResource(filename);

        if (file == null)
            return ResponseEntity.notFound().build();

        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

    @PostMapping("/handleFileUpload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {

        storageService.store(file);
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + file.getOriginalFilename() + "!");

        return "redirect:/fileUpload/form";
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }

}

3.加入以下类

@Service
public class FileSystemStorageService implements StorageService {

    private final Path rootLocation;

    @Autowired
    public FileSystemStorageService(StorageProperties properties) {

        if (properties.getLocation().trim().length() == 0) {
            throw new StorageException("File upload location can not be Empty.");
        }

        this.rootLocation = Paths.get(properties.getLocation());
    }

    @Override
    public void store(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                throw new StorageException("Failed to store empty file.");
            }
            Path destinationFile = this.rootLocation.resolve(
                            Paths.get(file.getOriginalFilename()))
                    .normalize().toAbsolutePath();
            if (!destinationFile.getParent().equals(this.rootLocation.toAbsolutePath())) {
                // This is a security check
                throw new StorageException(
                        "Cannot store file outside current directory.");
            }
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, destinationFile,
                        StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException e) {
            throw new StorageException("Failed to store file.", e);
        }
    }

    @Override
    public Stream<Path> loadAll() {
        try {
            return Files.walk(this.rootLocation, 1)
                    .filter(path -> !path.equals(this.rootLocation))
                    .map(this.rootLocation::relativize);
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }

    }

    @Override
    public Path load(String filename) {
        return rootLocation.resolve(filename);
    }

    @Override
    public Resource loadAsResource(String filename) {
        try {
            Path file = load(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new StorageFileNotFoundException(
                        "Could not read file: " + filename);

            }
        } catch (MalformedURLException e) {
            throw new StorageFileNotFoundException("Could not read file: " + filename, e);
        }
    }

    @Override
    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

    @Override
    public void init() {
        try {
            Files.createDirectories(rootLocation);
        } catch (IOException e) {
            throw new StorageException("Could not initialize storage", e);
        }
    }
}
@ConfigurationProperties("storage")
public class StorageProperties {

    /**
     * Folder location for storing files
     */
    private String location = "upload-dir";

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}
public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();
}
public class StorageException extends RuntimeException {

    public StorageException(String message) {
        super(message);
    }

    public StorageException(String message, Throwable cause) {
        super(message, cause);
    }
}
public class StorageFileNotFoundException extends StorageException {

    public StorageFileNotFoundException(String message) {
        super(message);
    }

    public StorageFileNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}

4.在resources里面加入templates,jiaru uploadForm.html

<html xmlns:th="https://www.thymeleaf.org">
<body>

<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>

<div>
    <form method="POST" enctype="multipart/form-data" action="/Scaffold/fileUpload/handleFileUpload">
        <table>
            <tr>
                <td>File to upload:</td>
                <td><input type="file" name="file"/></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Upload"/></td>
            </tr>
        </table>
    </form>
</div>

<div>
    <ul>
        <li th:each="file : ${files}">
            <a th:href="${file}" th:text="${file}"/>
        </li>
    </ul>
</div>

</body>
</html>

5.在启动类里面加入

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class UploadingFilesApplication {

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

	@Bean
	CommandLineRunner init(StorageService storageService) {
		return (args) -> {
			storageService.deleteAll();
			storageService.init();
		};
	}
}

启动项目,开始测试

点击选择文件,选择文件之后,点击upload,会出现以下界面

点击蓝色的部分,就可以下载了,并且可以看到服务器这里就是上传的文件了

目前重启服务器,上传的文件就会删除掉了,如果不想删除掉的话,启动类里面的代码可以是去掉storageService.deleteAll();这一行代码,变成为:

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class UploadingFilesApplication {

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

	@Bean
	CommandLineRunner init(StorageService storageService) {
		return (args) -> {
			storageService.init();
		};
	}
}

 

标签:String,上传下载,class,file,filename,本机,public,storageService,springboot
From: https://www.cnblogs.com/yunzhiliuandyunchaoliu/p/18190599

相关文章

  • springboot项目启动会报4个加载不到的debug提示,可改可不改
    1.因为启动的时候会报提示:UnabletolocateLocaleResolverwithname'localeResolver':usingdefault[org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@17162122]有4个这样的--Resolver,(具体每个Resolver在下面注释有说明)要想不报这个加载提示,如果用不......
  • 创建启动springboot项目的一些问题,如spring-boot-autoconfigure 自动加载注入配置
    1.springboot项目启动是否只需要3下面3个jar包<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.b......
  • springboot内嵌tomcat的实现原理
    目录一、tomcat运行原理的简单分析1.1Coyote1.2容器catalina二、用编码的方式启动tomcat一、tomcat运行原理的简单分析tomcat运行时可以简单分成两个大的模块,(1)负责处理socket连接并转换成request对象的部分,连接器Coyote(2)处理用户的请求的容器Catalina下面简单介绍......
  • Springboot自动配置原理
    在SpringBoot项目中的引导类上有一个注解@SpringBootApplication,这个注解是对三个注解进行了封装,分别是:@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan其中@EnableAutoConfiguration是实现自动化配置的核心注解。该注解通过@Import注解导入对应的配......
  • SpringBoot速记
    本篇以SpringBoot快速构建一个基础项目,在构建的同时记录相关的知识。常见的架构图: 其中,config中可以引入第三方的jar包controller中存放控制类一个简单的例子如下: mapper中存放对数据库的操作接口 pojo中是实体对象类,常与数据表对应 service中存放服务类:......
  • SpringBoot3集成WebSocket
    标签:WebSocket,Session,Postman。一、简介WebSocket通过一个TCP连接在客户端和服务器之间建立一个全双工、双向的通信通道,使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据,在WebSocket的API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创......
  • springboot的链路日志
    1.背景在开发银行项目的时候有一个生成项目链路日志的需求。所谓的链路日志就是一个请求会经过多个项目的接口调用,它把这个请求内调用到的所有请求通过全局id串起来,通过全局id可以把所有涉及到的系统日志都快速的定位出来,方便线上出现问题时去排查问题。2.实现......
  • springboot使用log4j监控日志发送邮件
    实现log4j发送邮件功能大致流程:1、开启邮箱SMTP服务,获取SMTP登录密码2、引入javax.mail、javax.activation依赖3、配置log4j文件,指定邮件发送方和接收方以及发送方账号密码等4、重写SMTPAppender(不重写也能实现邮件发送功能)开启邮箱SMTP服务这里以qq邮......
  • springboot项目服务器访问速度慢-可能的解决方法
    springboot项目部署在服务器后,访问很慢或无法访问问题使用宝塔界面,尝试将打包后的jar包部署在服务器上运行时,发现访问速度不是很快,或者是直接访问不到。访问不到对应端口的springboot服务80端口也无法访问首次访问加载慢的解决方法修改jre文件找到安装的jre目......
  • Springboot Data Jdbc中Contains和Containing的用法
    Contains和Containing的用法privateStringtitle;privateList<String>tags;//查询标题包含指定字符串的书籍List<Book>findByTitleContains(Stringtitle);//查询包含指定标签的书籍List<Book>findByTagsContaining(Stringtag);--查询标题包含"Spring"的书......