开发实例:后端Java和前端vue实现文件上传和下载功能

首先,在Java的后端代码中,我们可以使用Spring框架来实现文件上传和下载功能。以下是一个简单的示例:

文件上传

首先,我们需要在html页面上创建一个表单,其中包含一个file类型的输入字段:

<form action="/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="file" />
  <button type="submit">上传文件</button>
</form>

然后,在后端代码中,我们可以使用Spring框架的MultipartFile类来处理上传的文件,并将其保存到服务器上:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get("/path/to/upload/dir/" + file.getOriginalFilename());
            Files.write(path, bytes);
            return "上传成功:" + file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败:" + file.getOriginalFilename();
        }
    } else {
        return "上传失败:请选择要上传的文件!";
    }
}

在这个例子中,我们首先检查上传的文件是否为空,如果不为空,就读取文件的字节数据,并使用Files.write()方法将其写入指定的路径。

文件下载

对于文件下载,我们可以使用Spring框架的ResponseEntity类来将文件内容作为响应体返回给前端。以下是一个示例代码:

@ResponseBody
public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) {
    File file = new File("/path/to/download/dir/" + fileName);
    if (file.exists()) {
        try {
            byte[] fileBytes = Files.readAllBytes(file.toPath());
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=" + fileName);
            ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
            return responseEntity;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

在这个例子中,我们首先检查指定的文件是否存在。如果存在,我们就使用Files.readAllBytes()方法读取文件内容生成byte数组,并将其设置为响应体的内容。同时,我们还需要设置响应头信息,告诉浏览器将该响应的内容作为下载文件。

在vue前端代码中,我们可以使用axios发送POST请求来上传文件,使用window.open()方法来实现文件下载。以下是一个示例代码:

文件上传

<template>
  <div>
    <input type="file" @change="uploadFile">
  </div>
</template>

<script>
import axios from 'axios'

export default {
  methods: {
    uploadFile(e) {
      let formData = new FormData()
      formData.append('file', e.target.files[0])
      axios.post('/upload', formData)
        .then(response => {
          console.log(response.data)
        })
        .catch(error => {
          console.log(error.response.data)
        })
    }
  }
}
</script>

在这个例子中,我们只需要监听文件选择框的change事件,获取用户选择的文件,并使用FormData对象创建一个包含文件的表单数据。然后,我们使用axios.post()方法将表单数据发送给服务器。

文件下载

<template>
  <div>
    <button @click="downloadFile">下载文件</button>
  </div>
</template>

<script>
export default {
  methods: {
    downloadFile() {
      let fileName = 'example.txt'  // 要下载的文件名
      window.open('/download/' + fileName)
    }
  }
}
</script>

在这个例子中,我们只需要在按钮的click事件中调用window.open()方法,并将要下载的文件名拼接到URL中即可。由于文件下载是浏览器自身的行为,因此我们无法通过JavaScript代码直接控制,只能将该操作委托给浏览器处理。

参考文章:http://blog.ncmem.com/wordpress/2023/10/26/%e5%bc%80%e5%8f%91%e5%ae%9e%e4%be%8b%ef%bc%9a%e5%90%8e%e7%ab%afjava%e5%92%8c%e5%89%8d%e7%ab%afvue%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%92%8c%e4%b8%8b%e8%bd%bd%e5%8a%9f%e8%83%bd/
欢迎入群一起讨论

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用Vue.js和Java编写的前端后端递参数的例子: 前端代码(使用Vue.js): ```html <!DOCTYPE html> <html> <head> <title>Vue Example</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> new Vue({ el: '#app', data: { name: '', age: '', response: '' }, methods: { sendData() { axios.post('backend.php', { name: this.name, age: this.age }) .then(response => { this.response = response.data; }) .catch(error => { console.error(error); }); } } }); </script> </head> <body> <div id="app"> <input type="text" v-model="name" placeholder="Name"> <input type="text" v-model="age" placeholder="Age"> <button @click="sendData">Send Data</button> <div>{{ response }}</div> </div> </body> </html> ``` 后端代码(Java,使用Spring Boot): ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class BackendApplication { public static void main(String[] args) { SpringApplication.run(BackendApplication.class, args); } @PostMapping("/backend.php") public String processData(@RequestBody RequestData requestData) { String name = requestData.getName(); int age = requestData.getAge(); // 处理数据,这里只是简单地将数据拼接成字符串作为响应返回 String response = "Name: " + name + ", Age: " + age; return response; } public static class RequestData { private String name; private int age; // 添加默认构造函数和getter/setter方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } } ``` 在这个例子中,我们使用Vue.js在前端创建了一个简单的表单,包含了一个文本输入框用于输入姓名和年龄,并有一个按钮用于发送数据。我们使用`v-model`指令将输入框的值绑定到Vue实例的`name`和`age`属性上。 在Vue实例的`sendData`方法中,我们使用Axios库发送POST请求到后端的`/backend.php`接口,并将`name`和`age`作为请求体发送。在成功响应后,我们将后端返回的响应数据赋值给Vue实例的`response`属性,用于显示在页面上。 后端使用Spring Boot框架编写了一个简单的Java应用程序。我们创建了一个RESTful接口`/backend.php`,通过`@PostMapping`注解来处理POST请求。请求体中的数据会自动映射到`RequestData`类中的属性。在处理数据时,我们将姓名和年龄拼接成字符串作为响应返回。 请注意,需要安装Vue.js和Axios库,以及配置好Java开发环境和Spring Boot依赖。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值