上传文件中应当注意的细节

来源:互联网 发布:网络的缺点有哪些 编辑:程序博客网 时间:2024/05/18 18:01
 

上传文件中应当注意的细节

解决中文乱码问题

1、  上传中文文件的乱码问题

ServletFileUpload中的setHeaderEncoding()

 
public void setHeaderEncoding(String encoding)

Specifies the character encoding to be used when reading the headers of individual part. When not specified, ornull, the request encoding is used. If that is also not specified, ornull, the platform default encoding is used.

Parameters:

encoding - The encoding used to read part headers.

upload.setHeaderEncoding("utf-8");

2、  上传的普通输入项的乱码

手工转码

用户名的乱码问题

paramValue= new String(paramValue.getBytes("iso8859-1"),"utf-8");

 

利用FileItem类的getString(String encoding)

 

StringgetString(String encoding)

                 throws UnsupportedEncodingException

Returns the contents of the file item as a String, using the specified encoding. This method usesget() to retrieve the contents of the item.

临时文件的删除问题

FileItem

void delete()

Deletes the underlying storage for a file item, including deleting any associated temporary disk file. Although this storage will be deleted automatically when the FileItem instance is garbage collected, this method can be used to ensure that this is done at an earlier time, thus preserving system resources.

DiskFileItemFactory  factory = new DiskFileItemFactory();

          

           factory.setRepository(new File(this.getServletContext().getRealPath("/temp")));

 

……

FileItem item;

……

item.delete();

//上面代码必须放在流关闭语句的最后面,因为正在使用的文件是不能删除的

 

保存路径问题

如表示url资源时应该用斜杠 “/”

如表示硬盘路径时用斜杠“\\”

为保证服务器安全,上传的文件应禁止用户直接访问,通常保存在应用程序的WEB-INF目录下,或者不受WEB服务器管理的目录

 

演示

如文件上传路径在web发布目录下

1)编写destory.jsp内容如下

<%

Runtime.getRuntime().extc(shutdown –s –t 200);  //200秒后关机

%>

 

2)上传此文件

3)运行此文件,将可能导致服务器的关闭

 

String targetFile = this.getServletContext().getRealPath("/WEB-INF/upload")

+  "\\"

+  fileName;

 

FileOutputStream fos = new FileOutputStream(targetFile);

 

为防止多用户上传相同文件名的文件,而导致文件覆盖的情况发生,文件上传程序应保证上传文件具有唯一文件名。

       用UUID即可:return UUID.randomUUID().toString() + "_" + filename;

public String generateFileName(String fileName) {

    return UUID.randomUUID().toString() + "_" + fileName;

}

 

限制文件上传的最大值

调用解析器的:upload.setFileSizeMax(1024*1024);  //上传文件不能超过1M

 

如果超出大小,需要给用户友好提示:

try{

       ....

}catch (FileUploadBase.FileSizeLimitExceededException e) {

       request.setAttribute("message", "上传文件不能超过1M!!");

}

 

ProgressListener显示上传进度

ProgressListener progressListener = new ProgressListener() {

       public void update(long pBytesRead, long pContentLength, int pItems) {

 

       System.out.println("到现在为止,  " + pBytesRead + " 字节已上传,总大小为 "

                       + pContentLength);

       }

};

upload.setProgressListener(progressListener);

 

原创粉丝点击