当前位置:主页   - 电脑 - 程序设计 - JAVA
Java Servlet 编程及应用之八
来源:网络   作者:   更新时间:2012-06-10
收藏此页】    【字号    】    【打印】    【关闭

  Java Servlet 在网络上的编程应用,如利用Servlet 上传和下载文件、Servlet 的数据库编程、在Servlet 中发送和接受邮件以及Java Servlet 在RMI和XML等方面的应用,由于篇幅有限,在这里就不在多介绍了,下面再举一个Servlet 上传的例子。

  在Web 应用程序中,用户向服务器上传文件是非常普遍的操作。使用Servlet 实现文件的上传是比较简单的。

  编程思路:下面的UploadServlet.java ,其主要功能为从InputStream 中读取文件内容,将上传文件保存在根目录下,且文件名与上传文件的文件名一致。

  UploadServlet.java 的源代码如下:(代码节选)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UploadServlet extends HttpServlet
{
//default maximum allowable file size is 1000k
static final int MAX_SIZE = 1024000;
//instance variables to store root and success message
String rootPath, successMessage;
/**
* init method is called when servlet is initialized.
*/
public void init(ServletConfig config) throws ServletException
{
super.init(config);
//get path in which to save file
rootPath = config.getInitParameter("RootPath");
if (rootPath == null)
{
rootPath = "/";
}
/*Get message to show when upload is complete. Used only if
a success redirect page is not supplied.*/
successMessage = config.getInitParameter("SuccessMessage");
if (successMessage == null)
{
successMessage = "File upload complete!";
}
}
/**
* doPost reads the uploaded data from the request and writes
* it to a file.
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
{
ServletOutputStream out=null;
DataInputStream in=null;
FileOutputStream fileOut=null;
try
{
/*set content type of response and get handle to output
stream in case we are unable to redirect client*/
response.setContentType("text/plain");
out = response.getOutputStream();
//get content type of client request
String contentType = request.getContentType();
out.println("
contentType= " + contentType);
//make sure content type is multipart/form-data
if(contentType != null && contentType.indexOf(
"multipart/form-data") != -1)
{
//open input stream from client to capture upload file
in = new DataInputStream(request.getInputStream());
//get length of content data
int formDataLength = request.getContentLength();
out.println("
ContentLength= " + formDataLength);
//allocate a byte array to store content data
byte dataBytes[] = new byte[formDataLength];
//read file into byte array
int bytesRead = 0;
int totalBytesRead = 0;
int sizeCheck = 0;
while (totalBytesRead < formDataLength)
{
//check for maximum file size violation
sizeCheck = totalBytesRead + in.available();
if (sizeCheck > MAX_SIZE)
{
out.println("Sorry, file is too large to upload.");
return;
}
...........
...........

  编程e巧说明:

其它资源
来源声明

版权与免责声明
1、本站所发布的文章仅供技术交流参考,本站不主张将其做为决策的依据,浏览者可自愿选择采信与否,本站不对因采信这些信息所产生的任何问题负责。
2、本站部分文章来源于网络,其版权为原权利人所有。由于来源之故,有的文章未能获得作者姓名,署“未知”或“佚名”。对于这些文章,有知悉作者姓名的请告知本站,以便及时署名。如果作者要求删除,我们将予以删除。除此之外本站不再承担其它责任。
3、本站部分文章来源于本站原创,本站拥有所有权利。
4、如对本站发布的信息有异议,请联系我们,经本站确认后,将在三个工作日内做出修改或删除处理。
请参阅权责声明