在java编程中怎样处理文件上传?
1个回答
展开全部
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import com.jspsmart.upload.*;
public class UploadServlet extends HttpServlet {
/**
* 响应请求
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JspFactory _jspxFactory = null;
PageContext pageContext = null;
ServletConfig config = null;
// 变量定义
int count=0;
String result = "";
SmartUpload myUpload = new SmartUpload();
try {
_jspxFactory = JspFactory.getDefaultFactory();
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
config = pageContext.getServletConfig();
// 初始化
myUpload.initialize(config,request,response);
// myUpload.initialize(request);
// 上载
myUpload.upload();
// 保存上载文件到指定目录
// PATH为form表单提交过来的
count = myUpload.save(myUpload.getRequest().getParameter("PATH"));
System.out.println(myUpload.getRequest().getParameter("PATH"));
System.out.println("***********************");
// 显示处理结果
result = count + " file uploaded.";
} catch (Exception e){
result = " error. file not be uploaded.";
e.printStackTrace();
}
request.setAttribute("result",result);
RequestDispatcher rd = request.getRequestDispatcher("/jsp/result.jsp");
rd.forward(request,response);
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import com.jspsmart.upload.*;
public class UploadServlet extends HttpServlet {
/**
* 响应请求
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JspFactory _jspxFactory = null;
PageContext pageContext = null;
ServletConfig config = null;
// 变量定义
int count=0;
String result = "";
SmartUpload myUpload = new SmartUpload();
try {
_jspxFactory = JspFactory.getDefaultFactory();
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
config = pageContext.getServletConfig();
// 初始化
myUpload.initialize(config,request,response);
// myUpload.initialize(request);
// 上载
myUpload.upload();
// 保存上载文件到指定目录
// PATH为form表单提交过来的
count = myUpload.save(myUpload.getRequest().getParameter("PATH"));
System.out.println(myUpload.getRequest().getParameter("PATH"));
System.out.println("***********************");
// 显示处理结果
result = count + " file uploaded.";
} catch (Exception e){
result = " error. file not be uploaded.";
e.printStackTrace();
}
request.setAttribute("result",result);
RequestDispatcher rd = request.getRequestDispatcher("/jsp/result.jsp");
rd.forward(request,response);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询