Springboot 文件下载接口开发
这里写目录标题
具体思路
之前做了有关文件上传到服务器的相关工作,与之对应必然有人需要从服务器进行文件的下载操作,这里沿着上一阶段的路线接着做文件下载的相关操作。
实现
由于实体类在之前已经定义好了所以不再进行重复定义,FileUtils类里面需要添加一个函数
public static void filedownload(OutputStream os,String filepath){
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
byte[] buff = new byte[1024];
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, i);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(" download success");
}
此外,对应的FileResource类里面添加对应的dowload函数
public String Download(HttpServletResponse res,int fileId) throws IOException {
FileResource fr = filePathRepository.findById(fileId).get();
String fileName =fr.getFilename();
res.setHeader("content-type", "application/octet-stream");
res.setContentType("application/octet-stream");
res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
FileUtil.filedownload(res.getOutputStream(),fr.getPath());
return "succes dowload";
}
新建一个FileDownloadController
import com.example.login.service.FileResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class FileUploadController {
@Autowired
private FileResourceService filePathService;
@RequestMapping("/download")
@ResponseBody
public String downloadFile(@RequestParam("fileId") int fileId ,HttpServletResponse res) throws IOException {
return filePathService.Download(res,fileId);
}
}
测试方式如下由于postman对于接受的数据所展示的格式太少,经常会乱码,所以可以选择在浏览器输入这样的地址
http://localhost:8181/download?fileId=(对应文件id)
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/17786.html