Linux里可以创建软链接,如同Windows系统的快捷方式。如图:
Linux里创建软链接的语法:
ln -s 源文件 链接目录
ln -s /app/tomcat_file/uploadfiles uploadfiles
创建链接目录后,如图所示:
在一个SpringBoot项目里,如果把下载的文件存到 /usr/local/tomcat/webapps/ROOT/WEB-INF/uploadfiles里,这时若下载该链接目录里的文件时,可能会找不到文件。
针对不同的情况,有下述两种解决方式:
1.在下载的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();
}
}
}
}
通过上述方式,可以判断文件路径是普通路径还是链接路径,从而顺利下载文件。
2.如果使用上述方式后,仍不能下载Linux软链接里的文件,则可以采用这个方法:
找到tomcat根路径下的conf/context.xml,在<Context></Context>标签之间添加配置。
对于 Tomcat 7,在<Context>标签里加属性,具体为:<Context allowLinking="true" />。
对于Tomcat 8及以上的版本,在<Context></Context>标签之间添加子标签,具体为:
<Context>
<Resources allowLinking="true" />
</Context>
笔者用的Tomcat 9.0.43,配置如下:
配置后,重新启动Tomcat(若所用Tomcat配置了热加载则无需重新启动),可以发现,Linux软链接里的文件可以正常下载了。