[SpringBoot+Html]实现简单的文件上传并存储至本地,含前后端代码

 

1.前端upload.html

三要素:

        ①method="post"

        ②enctype="mutipart/form-data"

        ③type="file"

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>

    <!--上传文件,表单格式必须为"multipart/form-data" -->
    <form action="/upload" method="post" enctype="multipart/form-data">
        姓名: <input type="text" name="username"><br>
        年龄: <input type="text" name="age"><br>
        头像: <input type="file" name="image"><br>
        <input type="submit" value="提交">
    </form>

</body>
</html>

2. 后端UploadController.java

①服务端接收文件 参数:MultipartFile image

②获取原始文件名

③获取文件扩展名

④运用uuid构造唯一文件名

⑤将文件存储在服务器的磁盘目录

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
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.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {


    //本地存储文件
    @PostMapping("/upload")
    public Result upload(String username, Integer age, @RequestParam("image") MultipartFile file) throws IOException {
        log.info("文件上传:{},{},{}", username, age, file);
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件扩展名 123.2.1.jpg
        int index = originalFilename.lastIndexOf("."); //最后一个.的下标
        String extname = originalFilename.substring(index);
        //构造唯一的文件名(不能重复) -- uuid(通用唯一识别码)040bf482-284b-40a6-bf61-15c811d1b0d0
        String newFilename = UUID.randomUUID().toString() + extname;
        log.info("新的文件名:{}", newFilename);

        //将文件存储在服务器的磁盘目录中 D:\demo\files
        file.transferTo(new File("D:\\demo\\files\\"
                        + newFilename));
        return Result.success();
    }

}

注意:若上传的文件过大会报错,需在application.propertis或yml文件中配置文件大小

95181604af844f65a141db37087e16bb.png

启动服务器,测试:

 194115215c1841f4b29d286721c9b35b.png

18cb6b595fcf4bcf87df2448c713ffb1.png

请求成功!查看D:\demo\files也有对应上传的文件

 

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现前端上传文件到本地并将url存入本地数据库,需要前后端协同完成以下几个步骤: 1. 前端使用 Vue.js 实现文件上传,并将文件传递给后端。 2. 后端使用 Spring Boot 接收前端传递的文件,并将文件保存到本地。 3. 后端生成本地文件的URL,将URL保存到数据库中。 4. 前端从数据库中获取URL,展示文件信息。 以下是具体实现步骤: 1. 前端实现文件上传,使用 Vue.js 和 Axios 实现代码如下: ```html <template> <div> <input type="file" @change="onFileChange"> <button @click="uploadFile">上传</button> </div> </template> <script> import axios from 'axios'; export default { data() { return { file: null }; }, methods: { onFileChange(event) { this.file = event.target.files[0]; }, uploadFile() { const formData = new FormData(); formData.append('file', this.file); axios.post('/api/upload', formData).then(response => { console.log(response.data); }).catch(error => { console.log(error); }); } } }; </script> ``` 2. 后端使用 Spring Boot 接收前端传递的文件,并将文件保存到本地。代码如下: ```java @RestController @RequestMapping("/api") public class FileController { @Value("${file.upload-dir}") private String uploadDir; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { String filename = file.getOriginalFilename(); Path path = Paths.get(uploadDir, filename); Files.write(path, file.getBytes()); return "上传成功"; } } ``` 在 Spring Boot 中,使用 `@Value` 注解获取配置文件中的变量值,即上传文件存储的路径。 3. 后端生成本地文件的URL,将URL保存到数据库中。代码如下: ```java @RestController @RequestMapping("/api") public class FileController { @Autowired private FileRepository fileRepository; @Value("${file.base-url}") private String baseUrl; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { String filename = file.getOriginalFilename(); Path path = Paths.get(uploadDir, filename); Files.write(path, file.getBytes()); String url = baseUrl + filename; fileRepository.save(new FileEntity(filename, url)); return "上传成功"; } } ``` 在 Spring Boot 中,使用 `@Value` 注解获取配置文件中的变量值,即本地文件的URL前缀。 4. 前端从数据库中获取URL,展示文件信息。代码如下: ```html <template> <div> <div v-for="file in files" :key="file.id"> <a :href="file.url">{{ file.name }}</a> </div> </div> </template> <script> import axios from 'axios'; export default { data() { return { files: [] }; }, mounted() { axios.get('/api/files').then(response => { this.files = response.data; }).catch(error => { console.log(error); }); } }; </script> ``` 在 Vue.js 中,使用 `axios` 发送请求获取文件信息,展示文件的名称和URL。需要注意的是,文件的URL需要使用 `<a>` 标签展示,并且需要设置 `href` 属性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值