FileUpload.java
发表在JavaWeb图书答疑 2012-02-08
是否精华
版块置顶:
package com.cdd.servlet;

[strong]import java.io.*;
import java.util.Enumeration;
[/strong]
import javax.servlet.*;
import javax.servlet.http.*;
[font color=#FF0000]import com.jspsmart.upload.*;
import com.jspsmart.upload.File;
[/font]
public class FileUpload extends HttpServlet {

/**
 * The doGet method of the servlet. <br>
 * 
 * This method is called when a form has its tag value method equals to get.
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);

}

/**
 * The doPost method of the servlet. <br>
 * 
 * This method is called when a form has its tag value method equals to
 * post.
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
com.jspsmart.upload.SmartUpload su = new com.jspsmart.upload.SmartUpload();
String result = "没有确定要上传的文件!";   //设置返回信息字符串
String time = System.currentTimeMillis() + "";    //获取当前时间的毫秒数
String filedir = "upload/";
long maxsize = 1024 * 1024 * 5;   //定义最大上传文件的长度
try {
su.initialize(this.getServletConfig(), request, response); //初始化SmartUpload对象
su.upload();  //调用upload()方法
Files files = su.getFiles();  //获取所有上传文件
if (files.getSize() > maxsize) {  //判断上传文件的长度是否大于设置的最大文件长度
result = "文件大小超出范围";
}
for (int i = 0; i < files.getCount(); i++) { //获取遍历上传的所有文件
File singlefile = files.getFile(i);  //获取每个上传的文件对象
if ((!singlefile.isMissing()) && (files.getSize() < maxsize)) {
                                     //如果用户选择了上传文件,并且上传的文件小于限制的大小
String filedirs = new String(filedir + time + i + "."
+ singlefile.getFileExt());
//定义上传文件的名称
{
singlefile.saveAs(filedirs, File.SAVEAS_VIRTUAL); //保存文件
result = "文件上传成功!";
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("result", result); //将提示信息保存在request对象中
RequestDispatcher requestDispatcher =
分享到:
精彩评论 1
aster
学分:0 LV1
TA的每日心情
开心
2023-01-31 09:41:43
2012-02-08
沙发
读者您好:请问你想问什么问题?
首页上一页 1 下一页尾页 1 条记录 1/1页
手机同步功能介绍
友情提示:以下图书配套资源能够实现手机同步功能
明日微信公众号
明日之星 明日之星编程特训营
客服热线(每日9:00-17:00)
400 675 1066
mingrisoft@mingrisoft.com
吉林省明日科技有限公司Copyright ©2007-2022,mingrisoft.com, All Rights Reserved长春市北湖科技开发区盛北大街3333号长春北湖科技园项目一期A10号楼四、五层
吉ICP备10002740号-2吉公网安备22010202000132经营性网站备案信息 营业执照