日期:2014-05-16  浏览次数:20359 次

jsp+servlet上传文件,不用第三方jar包
//jsp
    <form action="UploadFile" method="post">
    <input type="file" name="file1" >
    <input type="file" name="file2">
    <input type="submit" value="上传">
    </form>

//servlet
public class UploadFile extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

List<String> fileList = new ArrayList<String>();
String filename1 = request.getParameter("file1");
String filename2 = request.getParameter("file2");

if (filename1 != null && filename1.trim().length() > 0) {
filename1= new String(filename1.getBytes("iso-8859-1"), "UTF-8");
fileList.add(filename1);
}

if (filename2 != null && filename2.trim().length() > 0) {
filename2 = new String(filename2.getBytes("iso-8859-1"), "UTF-8");
fileList.add(filename2);
}

System.out.println("filename1="+filename1 +"\r\n"+ "filename2="+filename2);

//建立上传文件存放的路径
File uploadPath = new File(request.getRealPath("/downloadPath"));
//System.out.println("uploadPath="+uploadPath);
if (!uploadPath.exists()) {
uploadPath.mkdirs();
}

for (int i = 0; i < fileList.size(); i++) {
String fileName[] = new String[fileList.size()];
String exFileName[] = new String[fileList.size()];

//文件路径
String filePath = fileList.get(i);
//取上传的文件名称
fileName[i] = filePath.substring(filePath.lastIndexOf("\\")+1, filePath.length());
//取得文件的扩展名称
exFileName[i] = filePath.substring(filePath.lastIndexOf(".")+1, filePath.length());

//在存放的目录下新建文件
File uploadFileName = new File(uploadPath, fileName[i]);
System.out.println("uploadFileName="+uploadFileName);
if (!uploadFileName.exists()) {
uploadFileName.createNewFile();
}

FileInputStream inputStream = new FileInputStream(filePath);
//向服务器写入文件
FileOutputStream outputStream = new FileOutputStream(uploadPath+"/"+fileName[i]);

int c = inputStream.read();
System.out.println("-----------c:"+c);
byte[] bt = new byte[1024];
int num = inputStream.read(bt, 0, 512);
while (num != -1) {
outputStream.write(bt, 0, 1024);
num = inputStream.read(bt, 0, 1024);
}

inputStream.close();
outputStream.close();

}
}

}