java下载文件前后端代码_java 附件上传、下载前后端代码
时间: 2024-01-19 20:02:49 浏览: 74
jquery批量上传, java后台批量上传下载无BUG对接,类似qq邮箱附件上传功能
5星 · 资源好评率100%
以下是Java后端的代码:
文件上传:
```java
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile multipartFile) {
try {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件的字节数组
byte[] bytes = multipartFile.getBytes();
// 设置文件存储路径
Path path = Paths.get("uploads/" + fileName);
// 将文件写入磁盘
Files.write(path, bytes);
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
}
```
文件下载:
```java
@GetMapping("/download")
public ResponseEntity<Resource> download(@RequestParam("fileName") String fileName) throws IOException {
// 获取文件的路径
Path path = Paths.get("uploads/" + fileName);
// 从磁盘读取文件内容
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
// 构建响应头
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(resource.contentLength()));
// 返回响应
return ResponseEntity.ok()
.headers(headers)
.body(resource);
}
```
以下是前端的代码:
文件上传:
```html
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"/>
<button type="submit">上传</button>
</form>
```
文件下载:
```javascript
function download(fileName) {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/download?fileName=' + fileName, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
};
xhr.send();
}
```
阅读全文