springboot+vue实现图片的上传和选择

依赖导入

 <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.7.7</version>
    </dependency>

文件上传和下载

在springboot项目下的controller层定义一个FileController类实现文件的上传和下载功能,如下:

@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${server.port}")
    private String port;
    private static final String ip = "http://localhost";

    /**
     * 上传接口
     * @param file
     * @return
     */

    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();//获取源文件的名称
	//        定义文件的唯一标识(前缀)
        String flag = IdUtil.fastSimpleUUID();

        String rootFilePath = System.getProperty("user.dir")+"/daxiongmao_backend/src/main/resources/files/"+flag+"_"+originalFilename;//获取文件上传的路径
        try {
            FileUtil.writeBytes(file.getBytes(),rootFilePath);//把文件写入该路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = ip+":"+port+"/files/"+flag;
        return Result.success(url);//返回结果url
    }

    /**
     * 下载接口
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response){
        OutputStream os;//新建一个输出对象
        String basePath = System.getProperty("user.dir")+"/daxiongmao_backend/src/main/resources/files/";//文件路径
        List<String> fileNames = FileUtil.listFileNames((basePath));//获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到根参数一致的文件

        try {
            if (StrUtil.isNotEmpty(fileName)){
                response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);//通过文件路径读取文字节流
                os = response.getOutputStream();//通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        }catch (Exception e){
            System.out.println("文件下载失败");
        }
    }
   }

vue上传图片

在与后端的controller层的添加方法相对应,在vue中通过表单输入添加的信息,action="http://localhost:8081/files/upload"是对于FileController中文件上传的地址。

   <el-form-item label="头像">
            <el-upload ref="upload" action="http://localhost:8081/files/upload" :on-success="filesUploadSuccess">
              <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>

在script中实现方法与后端对接:

export default {
name: 'User',
 components: {

 },
  data() {
	 return {
	 form:[]
	 }
},
 methods:{
 save(){
 request.post("/api/user",this.form).then(res =>{
      console.log(res);
      if (res.code==='0'){
        this.$message({
          type: "success",
          message: "新增成功"
        })
      }else {
        this.$message({
          type: "error",
          message: res.msg
        })
      }
 },
filesUploadSuccess(res){
  console.log(res);
  this.form.picture = res.data;
  this.load();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring BootVue.js都是非常流行的开发框架,它们可以很好地协同工作来实现上传图片的功能。 首先,你需要在Spring Boot中编写一个Controller来处理上传图片的请求。你可以使用Spring Boot的MultipartFile类来处理上传的文件。在Controller中,你可以使用@RequestBody注解来接收Vue.js发送的请求,并使用MultipartFile类来处理上传的文件。然后,你可以将上传的文件保存到服务器上的某个目录中。 在Vue.js中,你可以使用Vue.js的Axios库来发送上传图片的请求。你需要将上传的文件转换为FormData对象,并将其发送到Spring Boot的Controller中。在Vue.js中,你可以使用Vue.js的FileReader类来读取上传的文件,并将其转换为Base64编码的字符串。然后,你可以将Base64编码的字符串添加到FormData对象中,并使用Axios库将其发送到Spring Boot的Controller中。 总的来说,实现上传图片的功能需要在Spring BootVue.js中分别编写代码,并将它们协同工作。你需要在Spring Boot中编写Controller来处理上传图片的请求,并在Vue.js中使用Axios库发送请求并将上传的文件转换为FormData对象。 ### 回答2: 在使用Spring BootVue进行开发时,有时需要在页面中上传图片。本文将为您介绍如何使用Spring BootVue上传图片。 首先,在Vue组件中,可以使用input标签来选择上传的文件,并在触发change事件时将文件发送到后端。在Vue中,我们可以这样写: template: <template> <form> <input type="file" name="file" @change="uploadImage"> </form> </template> <script> export default { methods: { uploadImage(event) { let file = event.target.files[0]; let formData = new FormData(); formData.append("file", file); axios.post("/upload/image", formData, { headers: { "Content-Type": "multipart/form-data" } }).then(response => { // 处理上传成功后的逻辑 }).catch(error => { // 处理上传失败后的逻辑 }); } } } </script> 在这个例子中,我们使用了axios库来发送POST请求,并将文件作为FormData附加在请求中。后端的URL是“/upload/image”,这是您可以自由定义的。当服务器成功接收到文件时,它应该将文件保存在磁盘上。 下面是Java Spring Boot的后台代码,它将处理上传文件的请求。我们可以使用Spring的MultipartFile来处理上传的文件。这是服务器端的代码片段。 @RestController @RequestMapping("/upload") public class UploadController { @PostMapping("/image") public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) { try { // 获取文件名 String fileName = file.getOriginalFilename(); // 将文件保存在磁盘上 byte[] bytes = file.getBytes(); Path path = Paths.get("/your/upload/directory/" + fileName); Files.write(path, bytes); // 返回上传成功信息 return new ResponseEntity<>("上传成功!", HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); // 返回上传失败信息 return new ResponseEntity<>("上传失败!", HttpStatus.BAD_REQUEST); } } } 在这个例子中,我们使用了@PostMapping注释来处理上传文件的请求,这个请求将在“/upload/image”地址上发送。@RequestParam注释指明了我们将使用名称为“file”的参数来接受文件数据。当服务器成功接收到文件时,它将把它保存在磁盘上。实现上传文件功能时,需要注意文件上传的安全性。可通过设置文件大小限制和文件类型限制来增强安全性。 总之,通过VueSpring Boot,我们可以方便地实现图片上传功能。Vue提供了大量工具来处理文件,axios库可以很容易地将文件附加在请求中。Spring Boot的MultipartFile使我们能够轻松地处理来自前端的上传文件请求。在实现文件上传时,确保文件上传的安全性非常重要。 ### 回答3: Spring BootVue.js是两个非常流行和强大的Web开发框架和库。在现代Web开发中,上传和处理图像是非常普遍的需求。这篇文章将探讨如何使用Spring BootVue.js上传图像。 一、Spring Boot的文件上传 Spring Boot提供了很多上传文件的方法,其中最简单的方法是使用MultipartFile类。该类表示一个上传的图像文件,我们可以通过它来获取图像的文件名、大小、流等信息。下面是一个简单的Spring Boot控制器,可以接受一个图像文件的上传: ``` @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { String fileName = file.getOriginalFilename(); // 保存图像到磁盘 ... return "success"; } ``` 在上面的例子中,我们使用了@RequestParam注解来接收一个名为“file”的上传文件。然后,我们可以使用MultipartFile类的getOriginalFilename()方法来获取图像文件的原始文件名,也可以使用getInputStream()方法来获取图像文件的输入流。 如果我们想要限制上传文件的大小或类型,只需要在Spring Boot的配置文件中添加以下配置即可: ``` spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB spring.servlet.multipart.file-extension=jpg,png ``` 二、Vue.js的文件上传 下面是一个Vue.js组件,它可以上传一个图像文件到Spring Boot服务器: ``` <template> <div> <input type="file" @change="handleFileUpload" /> <button type="submit" @click="uploadFile">上传</button> </div> </template> <script> export default { data() { return { file: null, }; }, methods: { handleFileUpload(event) { this.file = event.target.files[0]; }, uploadFile() { let 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> ``` 上面的Vue.js组件包含一个文件输入字段和一个上传按钮。当用户选择一个图像文件后,handleFileUpload()方法将会被触发,将选择的文件保存到组件的file属性中。当用户单击“上传”按钮时,uploadFile()方法将会被触发,创建FormData对象,并将file属性添加到FormData中。最后,我们使用axios库来发送POST请求到Spring Boot服务器的/upload端点,将FormData作为请求体发送。如果上传成功,服务器将会返回一个“success”字符串。否则,我们将在控制台中看到一个错误消息。 三、综合例子 为了测试我们的上传组件,我们需要为Spring Boot服务器创建一个端点,它将保存上传的文件到本地磁盘。下面是一个简单的上传控制器,它将上传的文件保存到“/tmp/uploads”目录中: ``` @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { try { // 保存上传文件到本地磁盘 file.transferTo(new File("/tmp/uploads/" + file.getOriginalFilename())); return ResponseEntity.ok("success"); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } } ``` 我们可以用以下命令来启动Spring Boot服务器: ``` mvn spring-boot:run ``` 现在,我们可以将上面的Vue.js组件添加到我们的Vue.js应用程序中,并尝试上传一个图像文件。如果一切正常,我们将在控制台中看到“success”字符串,并在“/tmp/uploads”目录中找到上传的文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值