【问题标题】:Creating read only file when download下载时创建只读文件
【发布时间】: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,只需使用FileInputStreamskip(start)

标签: java spring-mvc multipart


【解决方案1】:

很遗憾,这是不可能的。

一旦文件位于您无法控制的用户计算机上,您就无法对该文件执行任何操作。

您可以使用密钥对其进行签名以检测篡改,他们仍然可以对其进行编辑,但您会知道他们已经这样做了。

您甚至无法设置只读标志,正如question 所确认的那样,因为没有只读标头,即使您制作了一个尊重此标头的下载器,并在文件上设置了用户可以的标志只需从文件中删除只读标志并能够对其进行编辑。

【讨论】:

    【解决方案2】:

    您必须为自己设置只读属性:

    file.setReadOnly();
    

    来自documentation of the setReadOnly method

    公共布尔 setReadOnly()

    标记由此抽象路径名命名的文件或目录,以便只允许读取操作。调用此方法后,文件或目录在被删除或标记为允许写入访问之前不会更改。在某些平台上,可以使用允许它修改标记为只读的文件的特殊权限启动 Java 虚拟机。是否可以删除只读文件或目录取决于底层系统。

    【讨论】:

    • 什么时候需要设置这个?下载文件后?
    • 是的,在创建文件之后。
    猜你喜欢
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多