java - 是否可以限制图像大小并仅上传特定大小

标签 java file-handling

我正在使用上面的代码上传文件,代码工作正常。

我的问题是,是否可以仅在图像上传期间将图像限制为 75 kb?

如果超过 75 kb,我不想抛出异常,而是继续上传我得到的内容

private void writeToFile(InputStream uploadedInputStream,String uploadedFileLocation) {
    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        int read = 0;
        byte[] bytes = new byte[1024];
        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

最佳答案

public final static int MAX_SIZE = 75000;

private void writeToFile(InputStream uploadedInputStream,String uploadedFileLocation) {
    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        int read = 0;
        int size = 0;
        byte[] bytes = new byte[1024];
        out = new FileOutputStream(new File(uploadedFileLocation));
        while (size < MAX_SIZE && (read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
            size += read;
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

关于java - 是否可以限制图像大小并仅上传特定大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32071206/

相关文章:

java - 如何在运行时加载接口(interface)的实现并调用该类的方法?

java - 在 Android 应用程序中发送/接收短信(作为默认短信应用程序)

java - 将 3rd 方库与 Maven 构建集成

javascript - 从另一个目录下载文件 AngularJS

c++ - 在 C++ 中使用 RWCString 读取文本文件时获取 RWBoundsErr

java - 如何让 Ant 更喜欢链接 JAR 中的类而不是 JDK 类?

java - 将颜色代码与颜色进行比较

文件或无的 Python 上下文

std::basic_ifstream 上的 C++ 编译错误

c++ - 将字符串与文件中的数据进行比较