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

时间:2015-08-18 11:30:55

标签: java file-handling

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

我的问题是,是否可以在图像上传期间将图像限制为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();
    }
}

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

有各种方法可以做到这一点。如果您使用 Struts ,请编辑Strtus.xml并使用where where值表示文件大小限制

<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>

<强>爪哇

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

答案 2 :(得分:0)

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

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

  }else{

    }