上傳成功之后,用 request.getParameter("filetxt");拿到的是一個(gè)路徑:C:fakepathtest.txt
這個(gè)路徑并非是我本地的路徑,已上傳就已經(jīng)是這個(gè)路徑了。
現(xiàn)在我用了一個(gè)方法,來計(jì)算這個(gè)文件的大小,但是沒有成功,不知道為什么?
計(jì)算大小的方法如下:
public void getFileSize(String path){
//傳入文件路徑
File file = new File(path);
//測(cè)試此文件是否存在
if(file.exists()){
//如果是文件夾
//這里只檢測(cè)了文件夾中第一層 如果有需要 可以繼續(xù)遞歸檢測(cè)
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("此文件不存在");
}
}
調(diào)用方法:
String filetxt = request.getParameter("filetxt");
fileSize.getFileSize(filetxt);
(filetxt = "C:fakepathtest.txt")
結(jié)果是:此文件不存在
ringa_lee
The format of file upload and transmission is different from that of general form submission. It uses multipart/form-data
格式編碼數(shù)據(jù),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 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"); // 對(duì)應(yīng) <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 documentationservlet3.0(Tomcat7)
以下版本,需要第三方jar
包來幫助解析上傳的文件。一般使用Apache的commons-fileupload
、commons-fileupload-io
. For specific usage, please refer to the official documentation. I won’t go into details
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.