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

Is it possible to Restrict Image size and upload only of certain size

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

我的问题是,是否可以在上传图片时将图片限制为 75 kb??

万一它超过 75 kb,我不想抛出 exception,而是继续上传我得到的

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();
    }
}

有多种方法可以做到这一点。如果您使用 Struts 然后编辑 Strtus.xml 并使用 其中值表示文件大小限制

<constant name="struts.multipart.maxSize" value="30000000" />

Servlet

@MultipartConfig(
location="/tmp", 
fileSizeThreshold=1024*1024,    // 1 MB
maxFileSize=1024*1024*5,        // 5 MB 
maxRequestSize=1024*1024*5*5    // 25 MB
)

<max-file-size>20848820</max-file-size>

Java

final static int MAX_SIZE = 50000;//Max Limit of File

您可以使用以下代码以 kb 为单位计算文件大小。

 long fileSize = file.length()/1024;
 System.out.println("fileSize="+fileSize);
 if(fileSize==75){

  }else{

    }