上传成功之后,用 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")
结果是:此文件不存在
The format of file upload and transmission is different from that of general form submission. It uses
multipart/form-data
格式编码数据,request.getParameter
only key-value pairs can be obtained. The file needs special processing and is mainly divided into two parts.Front desk processing, confirm your front desk
form
表单的enctype
属性为multipart/form-data
, example:Background processing.
tomcat7
以上可直接使用原生APIHttpServletRequest.getPart()
,在servlet
中:For specific usage, please refer to the javaee documentation
servlet3.0(Tomcat7)
以下版本,需要第三方jar
包来帮助解析上传的文件。一般使用Apache的commons-fileupload
、commons-fileupload-io
. For specific usage, please refer to the official documentation. I won’t go into detailsfile.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.