springboot 获取并保存文件

本文介绍了如何在SpringBoot应用中接收并保存前端异步上传的文件,包括后端处理代码和前端代码示例。提供的示例不仅限于图片,任何大小在1MB以内的文件都适用。项目Demo可通过提供的百度网盘链接下载,提取码为xpq1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下给出一种springboot获取并保存前端传递的文件的方式:
前端拟采取ajax异步传输FormData,后端拟采取用MultipartFile类型接收并保存。


先附后端代码:

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

import java.io.FileOutputStream;
import java.io.IOException;

@RestController
public class UpPic {
    @PostMapping("/uppic")
    String uppic(@RequestParam("data") MultipartFile file) {
        //System.out.println("进入后台成功");
        String pathName = "myURL";//想要存储文件的地址
        String pname = file.getOriginalFilename();//获取文件名(包括后缀)
        pathName += pname;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pathName);
            fos.write(file.getBytes()); // 写入文件
            //System.out.println("文件上传成功");
            return "文件上传成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败";
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

前端代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8" />
    <title>Title</title>
    <script th:src="@{../jquery.js}" ></script>
    <script>
        function sc(){
            var animateimg = $("#f").val(); //获取上传的图片名 带//
            var imgarr=animateimg.split('\\'); //分割
            var myimg=imgarr[imgarr.length-1]; //去掉 // 获取图片名
            var houzui = myimg.lastIndexOf('.'); //获取 . 出现的位置
            var ext = myimg.substring(houzui, myimg.length).toUpperCase();  //切割 . 获取文件后缀

            var file = $('#f').get(0).files[0]; //获取上传的文件
            var fileSize = file.size;           //获取上传的文件大小
            var maxSize = 1048576;              //最大1MB

                var data = new FormData();
                data.append("data",document.getElementById("f").files[0]);
                $.ajax({
                    url: "/uppic",
                    type: 'POST',
                    data: data,
                    dataType: 'JSON',
                    cache: false,
                    processData: false,
                    contentType: false
                }).done(function(ret){
                    if(ret['isSuccess']){
                        var result = '';
                        var result1 = '';
                        // $("#show").attr('value',+ ret['f'] +);
                        result += '<img src="' + '__ROAD__' + ret['f']  + '" width="100"/>';
                        result1 += '<input value="' + ret['f']  + '" name="user_headimg" style="display:none;"/>';
                        $('#result').html(result);
                        $('#show').html(result1);
                        layer.msg('上传成功');
                    }else{
                        layer.msg('上传失败');
                    }
                });
                return false;

        }
    </script>
</head>
<body>
<form id="form1">
    <label>头像</label>
    <input type="button" value="上传图片" "f.click()" class="btn_mouseout"/><br />
    <p><input type="file" id="f" name="f" "sc(this);" style="display:none"/></p>
</form>
<div id="result"></div>

</body>
</html>

前端代码中写的是“上传图片”,但实际上只要小于1m的文件(不只是图片)都可以传输。


上传文件项目demo下载地址:
链接:https://pan.baidu.com/s/1w2RyK34V7geGMMrQ7X9V4Q
提取码:xpq1

### 如何在 Spring Boot 中获取文件路径 在 Spring Boot 应用程序中,可以通过多种方式来获取文件路径。以下是几种常见的方式: #### 使用 `ResourceLoader` 获取资源路径 Spring 提供了 `ResourceLoader` 接口用于加载各种类型的资源。这使得可以轻松访问静态文件、模板和其他资源。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; public class FilePathUtil { private final ResourceLoader resourceLoader; @Autowired public FilePathUtil(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public String getFileUrl(String filePath) throws Exception { Resource resource = resourceLoader.getResource("classpath:" + filePath); return resource.getURL().toString(); } } ``` 此代码片段展示了如何利用 `ResourceLoader` 来定位返回给定路径下的文件 URL[^1]。 #### 通过环境变量或配置文件指定路径 另一种方法是从应用的配置文件(如 `application.properties` 或者 `application.yml`)或者环境变量中读取预定义好的文件位置信息。 对于 properties 文件来说: ```properties file.upload-dir=/path/to/upload/directory/ ``` 而在 yml 文件里则可能是这样的形式: ```yaml file: upload-dir: /path/to/upload/directory/ ``` 之后就可以借助于 `@Value` 注解注入这些值到 Bean 当中去使用[^2]。 #### 利用操作系统特定的位置存储临时文件或其他数据 有时可能需要创建临时文件或将某些数据保存在一个不会被频繁清理的地方。这时可以根据操作系统的不同选择合适的位置来进行处理。例如,在 Linux 上通常会选择 `/tmp/`, 而 Windows 可能更倾向于 `%TEMP%`. 为了使这段逻辑更加通用化,建议采用如下所示的方式来决定最终的目标目录: ```java import java.nio.file.Path; import java.nio.file.Paths; public class SystemPathResolver { public Path resolveSystemSpecificTempDir() { String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("win")) { return Paths.get(System.getenv("TEMP")); } else { // Assume Unix-like system by default. return Paths.get("/tmp"); } } } ``` 这种方法能够适应不同的部署环境,确保应用程序能够在任何支持的操作系统平台上正常工作[^3].
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值