【发布时间】:2018-02-19 08:29:50
【问题描述】:
我的要求是使用 spring mvc 上传只读格式的文件并以只读方式下载相同的文件。 我能够以只读格式上传文件,但下载后它丢失了只读属性。
文件上传代码:-
File destinationFile = new File ( targetPath);
try {
FileOutputStream out = new FileOutputStream( destinationFile );
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(out);
stream.write(bytes);
destinationFile.setReadOnly();
destinationFile.setWritable(false);
}finally {
if(stream != null){
stream.close();
}
}
下载代码:-
File file = new File(folderPath);
contentType = "application/octet-stream";
response.setBufferSize(BUFFER_SIZE);
response.setHeader("Content-Disposition", disposition + ";filename=\"" + filename + "\"");
RandomAccessFile input = new RandomAccessFile(file, "r");
OutputStream output = response.getOutputStream();
long start, long length;
byte[] buffer = new byte[BUFFER_SIZE];
int read;
if (input.length() == length) {
while ((read = input.read(buffer)) > 0) {
output.write(buffer, 0, read);
}
} else {
input.seek(start);
long toRead = length;
while ((read = input.read(buffer)) > 0) {
if ((toRead -= read) > 0) {
output.write(buffer, 0, read);
} else {
output.write(buffer, 0, (int) toRead + read);
break;
}
}
}
有什么建议吗?
【问题讨论】:
-
你的意思是一旦有人下载了文件,他们就可以编辑它吗?
-
不应该是只读格式。无法编辑。
-
您应该先关闭文件,然后再将其设置为只读。您在第二种情况下的下载代码看起来不正确。你永远不应该写的比你刚读的多。我不明白为什么在这里需要两个复制循环,或者
RandomAccessFile:如果start > 0,只需使用FileInputStream和skip(start)。
标签: java spring-mvc multipart