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

 

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

解决中文乱码问题

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, or null, the request encoding is used. If that is also not specified, or null, 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)

 

String getString(String encoding)

                 throws UnsupportedEncodingException

Returns the contents of the file item as a String, using the specified encoding. This method uses get() 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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值