Linux里可以创建软链接,如同Windows系统的快捷方式。如图:

Linux里创建软链接的语法:
ln -s 源文件 链接目录
ln -s /app/tomcat_file/uploadfiles uploadfiles
创建链接目录后,如图所示:

在一个SpringBoot项目里,如果把下载的文件存到 /usr/local/tomcat/webapps/ROOT/WEB-INF/uploadfiles里,这时若下载该链接目录里的文件时,可能会找不到文件。
解决方式在下载的Controller里,进行下述处理:
package cn.lzy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
@RequestMapping("/attachment/accept")
public class AttachmentDownloadController extends CommonAttachmentController {
@Autowired
private ICommonAttachmentService commonAttachmentService;
@RequestMapping(value = "/downloadByAttachmentId.action", method = {RequestMethod.POST, RequestMethod.GET})
public void downloadByIdDo(HttpServletResponse response, String id) throws IOException {
ServletOutputStream out = null;
try {
CommonAttachment attachment = new CommonAttachment();
attachment.setId(id);
attachment = commonAttachmentService.queryOne(attachment);
String path = URLDecoder.decode(attachment.getAttachmentPath(), "utf-8");
path = UtilAttachmentPath.getDiskBaseFilePath(path);
String fileName = URLDecoder.decode(attachment.getAttachmentName(), "utf-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "filename=" + new String(fileName.getBytes("gb2312"), "iso8859-1"));
out = response.getOutputStream();
/*判断是否软链接文件,并区分软链接与普通文件进行读取.*/
Path target = FileSystems.getDefault().getPath(path.trim());
boolean isSoftLink = Files.isSymbolicLink(target);
if(isSoftLink){
Files.copy(Files.readSymbolicLink(target), out);
}else {
Files.copy(Paths.get(path.trim()), out);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw e;
}finally {
if(out != null){
out.close();
}
}
}
}
通过上述方式,可以判断文件路径是普通路径还是链接路径,从而顺利下载文件。
版权声明:本文为weixin_37654790原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。