您的位置:首页 > 其它

web开发之文件上传-王少飞的个人总结及案例

2012-11-29 21:15 483 查看
1.整理上课笔记

①上传文件名是中文:

upload.setHeaderEncoding("UTF-8");

②如果上传的是普通输入项,中文处理:

手工编码:inputValue = new String(inputValue.getBytes("iso8859-1"),"UTF-8");

通过getString(): String inputValue = item.getString("UTF-8");

③如果有没有填写的输入项:

if(!fileName.equals("")){ 。。。。 }

④删除临时文件:item.delete(); //删除item对应临时文件

⑤为保证服务器安全,上传文件应保存在应用程序的WEB-INF目录下,或者不受WEB服务器管理的目录。

⑥处理同名:UUID

⑦为防止单个目录下文件过多,影响文件读写速度,处理上传文件的程序应根据可能的文件上传总量,选择合适的目录结构生成算法,将上传文件分散

通过上传文件的hashcode产生文件夹存放。

2.实现文件的上传,和各细节。

上传的jsp页面--------------------

<%@ page Xlanguage="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>My JSP 'upload.jsp' starting page</title>

</head>

<body>

<form action="UploadServlet" enctype="multipart/form-data" method="post">

用户名:

<input type="text" name="username">

<br>

上传文件一:

<input type="file" name="file1">

<br>

上传文件二:

<input type="file" name="file2">

<br>

<input type="submit" value="上传">

<br>

</form>

</body>

</html>

返回上传结果的jsp页面--------------------

<%@ page Xlanguage="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>My JSP 'message.jsp' starting page</title>

</head>

<body>

${message}

</body>

</html>

处理上传的servlet---------------------

package com.hbsi.servlet;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.List;

import java.util.UUID;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.security.sasl.ServerFactoryImpl;

public class UploadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

try {

// 创建一个解析工厂

DiskFileItemFactory factory = new DiskFileItemFactory();

String tempPath=this.getServletContext().getRealPath("temp");

factory.setRepository(new File(tempPath));

// 得到一个解析器

ServletFileUpload upload = new ServletFileUpload(factory);

upload.setHeaderEncoding("UTF-8");

// 将请求传入解析器,对请求进行解析

List<FileItem> list = upload.parseRequest(request);

// 迭代list集合,得到每个输入项的数据

for (FileItem item : list) {

if (item.isFormField()) {

// 普通输入项

String inputName = item.getFieldName();

String inputValue = item.getString("UTF-8");

System.out.println(inputName + ":" + inputValue);

} else {

// 上传输入项

String fileName = item.getName();

if (!fileName.equals("")) {

fileName = fileName.substring(fileName

.lastIndexOf("\\") + 1);

String saveName=this.generateFileName(fileName);

InputStream in = item.getInputStream();

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

String savePaths = this.generateFilePath(savePath, fileName);

FileOutputStream out = new FileOutputStream(

savePaths+"\\" + saveName);

byte[] buf = new byte[1024];

int len = 0;

while ((len = in.read(buf)) > 0) {

out.write(buf, 0, len);

}

in.close();

out.close();

item.delete();

}

}

request.setAttribute("message", "上传成功");

}

} catch (Exception e) {

e.printStackTrace();

request.setAttribute("message", "上传失败");

}

request.getRequestDispatcher("/message.jsp").forward(request, response);

}

public String generateFileName(String filename){

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

}

public String generateFilePath(String path,String filename){

int dir1 =filename.hashCode()& 0xf;

int dir2 =(filename.hashCode()>>4) &0xf;

String savePath = path+"\\"+dir1+"\\"+dir2;

File f = new File(savePath);

if(!f.exists()){

f.mkdirs();

}

return savePath;

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: