java中文件上传下载的代码及注释
时间: 2023-11-28 09:49:59 浏览: 31
文件上传代码及注释如下:
```java
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@Value("${file.upload.path}")
private String uploadPath; // 上传文件的路径,从配置文件中读取
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) { // 判断上传的文件是否为空
return "redirect:/error";
}
// 生成一个唯一的文件名
String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
File destFile = new File(uploadPath + "/" + fileName);
try {
file.transferTo(destFile); // 将文件保存到磁盘中
return "redirect:/success";
} catch (IOException e) {
e.printStackTrace();
return "redirect:/error";
}
}
}
```
文件上传的主要逻辑是通过 `MultipartFile` 类型的参数来接收上传的文件,然后将其保存到指定的路径中。
文件下载代码及注释如下:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class FileController {
@Value("${file.upload.path}")
private String uploadPath; // 上传文件的路径,从配置文件中读取
@GetMapping("/download/{fileName:.+}")
public void downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response) {
File file = new File(uploadPath + "/" + fileName);
if (!file.exists()) { // 判断文件是否存在
return;
}
try (FileInputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
byte[] buffer = new byte[4096];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
文件下载的主要逻辑是通过 `HttpServletResponse` 类型的参数来向客户端输出文件。在输出文件之前,需要设置响应头,包括内容类型和文件名。然后读取文件内容并写入输出流中即可。