文件传输到服务器 servlet

来源:互联网 发布:网络层协议 编辑:程序博客网 时间:2024/05/20 10:14
upload.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>文件上传</title>
</head>
<body>                                           
<form action="../Upload" method="post" enctype="multipart/form-data">
<input type="file" name="file1"/><br/>
<input type="submit"/>
</form>
</body>
</html>

Upload .java

package com.cqc.lesson004.file_upload_server.upload;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Upload extends HttpServlet{

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
//得到输入流InputStream
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
FileItemIterator iter=upload.getItemIterator(req);
FileItemStream stream=iter.next();
InputStream input=stream.openStream();
//获得文件后缀
String fileSuffix=stream.getName();
fileSuffix=fileSuffix.substring(fileSuffix.lastIndexOf("."));
//获取系统时间
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
String time=sdf.format(date);
//获取存储位置
//1、得到HttpSession
//2、得到ServletContext
String path=req.getSession().getServletContext().getRealPath("/")+time+fileSuffix;
FileOutputStream output=new FileOutputStream(path);
//传输
byte[] b=new byte[1024];
int length=0;
while((length=input.read(b))>0){
output.write(b, 0, length);
}
input.close();
output.close();
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


1 0
原创粉丝点击