java - input file类型上传了一个文件,想计算一下上传文件的大小?
ringa_lee
ringa_lee 2017-04-18 10:51:20
0
3
643

上传成功之后,用 request.getParameter("filetxt");拿到的是一个路径:C:fakepathtest.txt
这个路径并非是我本地的路径,已上传就已经是这个路径了。
现在我用了一个方法,来计算这个文件的大小,但是没有成功,不知道为什么?
计算大小的方法如下:

public void getFileSize(String path){
        //传入文件路径
        File file = new File(path);
        //测试此文件是否存在
        if(file.exists()){
            //如果是文件夹
            //这里只检测了文件夹中第一层 如果有需要 可以继续递归检测
            if(file.isDirectory()){
                int size = 0;
                for(File zf : file.listFiles()){
                    if(zf.isDirectory()) continue;
                    size += zf.length();
                }
                System.out.println("文件夹 "+file.getName()+" Size: "+(size/1024f)+"kb");
            }else{
                System.out.println(file.getName()+" Size: "+(file.length()/1024f)+"kb");
            }
        //如果文件不存在
        }else{
            System.out.println("此文件不存在");
        }
    }
    

调用方法:
String filetxt = request.getParameter("filetxt");
fileSize.getFileSize(filetxt);

(filetxt = "C:fakepathtest.txt")

结果是:此文件不存在

ringa_lee
ringa_lee

ringa_lee

reply all(3)
伊谢尔伦

The format of file upload and transmission is different from that of general form submission. It uses multipart/form-data格式编码数据,request.getParameteronly key-value pairs can be obtained. The file needs special processing and is mainly divided into two parts.

  • Front desk processing, confirm your front deskform表单的 enctype属性为multipart/form-data, example:

    <form enctype="multipart/form-data" method="post" action="xxx">
      <input type="file" name="file" id="file" multiple /><br/>
    </form>
  • Background processing. tomcat7以上可直接使用原生API HttpServletRequest.getPart(),在servlet中:

    Part filePart = request.getPart("file"); // 对应 <input type="file" name="file">
    long bytes = filePart.getSize(); //获取文件大小
    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();//文件名
    InputStream fileContent = filePart.getInputStream(); //获取文件输入流

For specific usage, please refer to the javaee documentation
servlet3.0(Tomcat7)以下版本,需要第三方jar包来帮助解析上传的文件。一般使用Apache的commons-fileuploadcommons-fileupload-io. For specific usage, please refer to the official documentation. I won’t go into details

Peter_Zhu

file.exists() returns false. It can be seen from your file path that it is missing. You need to check which process it is filtered out.

巴扎黑

The path to upload the file to you is C:fakepathtest.txt. You can tell from this name that this is a fake path.

This path is given to you by the browser when it is uploaded to you. This path is not the path that actually exists on your server. So if you use this path to find this file on the server, it is impossible to find it.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!