springboot传照片,获取照片

自我记录  自我记录。。

源码下载地址:https://download.csdn.net/download/privatechen/10463674

之前用tomcat上传以及获取图片,图片的上传一般是放在tomcat中,项目中的文件夹下,但是当使用springboot打成的jar包时,此时上传图片便不能直接传入项目的根文件夹中了,因为整个项目打成了一jar包,不可拆分,此时,可以将图片传输到项目之外的文件夹下。

这里记录下如何将图片传送到springboot项目之外的文件夹下,并且如何从该文件夹下获取图片并展示到界面上

上传

 上传这个比较简单,springboot官网上就有示例可用,这里更精简一下,这个例子里只有四个文件:

1、启动类

@SpringBootApplication
(exclude = {DataSourceAutoConfiguration.class})
public class App {

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

 

2、Controller

 

    

@Controller
public class FileUploadController {


    // 这里的是application.properties中配置的地址
    @Value("${uploadpic.path}")
    private String uploadPicPath;


    // 主界面
    @GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {


        model.addAttribute("messages", "cpxxxxx");
        return "uploadPic";
    }


    // 文件上传按钮action
    @PostMapping("/uploadPic")
    public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes, Model model) throws Exception {


        // 存储图片到本地
        storePic(file);
        redirectAttributes.addFlashAttribute("message", "成功上传" + file.getOriginalFilename() + "!");
        System.out.println("上传的文件名字:" + file.getOriginalFilename());
        model.addAttribute("picName", file.getOriginalFilename()); // 将文件传输成功之后的名字传回界面,用于展示图片
        return "uploadPic";
    }


    private String storePic(MultipartFile file) throws Exception {
        String filename = StringUtils.cleanPath(file.getOriginalFilename());
        try {


            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, Paths.get(uploadPicPath + filename), // 这里指定了下载的位置
                    StandardCopyOption.REPLACE_EXISTING);
            }
        }
        catch (IOException e) {
            throw new Exception("失败!" + filename, e);
        }
        return filename;
    }
}

 

3、界面

 

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

	<div th:if="${message}">
		<h2 th:text="${message}"/>
	</div>
        
	<div>
		<form method="POST" enctype="multipart/form-data" action="/uploadPic"> <!--这里可以限制文件后缀-->
			<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>
		此处展示上传后的图片:<img th:src="${picName}"/> 
	</div>

</body>
</html>

 

4、配置文件application.properties

 

server.port=11111


 
uploadpic.path = F:/uploadPic/
#这里这两个是关键,没有这两个配置,前台获取不到图片,映射路径到指定路径,这里是把localhost:11111路径映射到了F:/uploadPic/下
#界面上的图片路径如果为localhost:11111/abc.jpg   这个路径会映射到    F:/uploadPic/abc.jpg下
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:${uploadpic.path}

 

获取

 

在配置文件application.properties中加上这两句配置即可。。。其实上面的已经可以在界面获取到图片了,主要是映射问题

 

spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:${uploadpic.path}

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Spring Boot编写一个批量下载照片的功能。以下是一个简单的示例代码: 1. 首先,您需要创建一个Controller类来处理下载请求: ```java @RestController @RequestMapping("/photos") public class PhotoController { @GetMapping("/download") public void downloadPhotos(HttpServletResponse response) throws IOException { // 设置响应头信息,指定为zip文件类型 response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=\"photos.zip\""); // 创建一个输出流,将文件写入到zip文件中 try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) { // 获取照片列表,这里假设您已经有了一个照片列表的数据源 List<String> photoUrls = getPhotoUrls(); // 遍历照片列表,逐个将照片写入到zip文件中 for (String photoUrl : photoUrls) { // 获取照片文件名 String fileName = photoUrl.substring(photoUrl.lastIndexOf("/") + 1); // 创建一个URL对象,用于下载照片 URL url = new URL(photoUrl); // 打开URL连接,并获取输入流 try (InputStream inputStream = url.openStream()) { // 将输入流写入到zip文件中 zipOut.putNextEntry(new ZipEntry(fileName)); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) > 0) { zipOut.write(buffer, 0, len); } zipOut.closeEntry(); } } } catch (IOException e) { e.printStackTrace(); } } private List<String> getPhotoUrls() { // 返回您的照片URL列表的方法,您可以从数据库或其他数据源获取照片URL列表 List<String> photoUrls = new ArrayList<>(); photoUrls.add("https://example.com/photo1.jpg"); photoUrls.add("https://example.com/photo2.jpg"); photoUrls.add("https://example.com/photo3.jpg"); return photoUrls; } } ``` 2. 在您的Spring Boot应用程序的配置类中,添加以下配置以允许跨域访问: ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("*") .allowedOrigins("*") .allowedHeaders("*"); } } ``` 3. 运行您的Spring Boot应用程序,并访问`http://localhost:8080/photos/download`,即可下载包含照片的zip文件。 请注意,上述代码仅供参考,您需要根据实际需求进行适当的修改和优化。例如,您可能需要更好地处理异常、验证请求、改进文件下载方式等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值