File Upload_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > File Upload

File Upload

 2014/6/13 18:35:05  Jon_Ronson  程序员俱乐部  我要评论(0)
  • 摘要:/***servlet代码*/publicclassUploadServletextendsHttpServlet{publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{DiskFileItemFactoryfactory=newDiskFileItemFactory()
  • 标签:file
class="java">
/**
 * servlet 代码
 */
public class UploadServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();//磁盤對象 存放臨時文件
ServletFileUpload sfu=new ServletFileUpload(factory);//声明 解析request对象
try{
   List<FileItem> items=sfu.parseRequest(request); //创建解析
   for(int i=0;i<items.size();i++){
   FileItem item=items.get(i);
   if(item.isFormField()){//普通文本
   String name=item.getString();
}else{
   ServletContext sct=getServletContext();
   String path=sct.getRealPath("images");//文件的保存路径
   String fileName1=item.getName();//传入文件的路径
   String fileName=fileName1.substring(fileName1.lastIndexOf("\\")+1);//获得文件名字
      File file=new File(path+"\\"+fileName);	
      response.sendRedirect("success.jsp");
try {
      item.write(file);
} catch (Exception e) {		
    e.printStackTrace();
   }				
}
  }
} catch (FileUploadException e) {
    e.printStackTrace();
    }		
  }
}


/**
 * jsp 页面
 */
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
    <title>File Upload</title>
 </head>
<body>
<form action="<%=path%>/UploadServlet" method="post" enctype="multipart/form-data">
 <fieldset>
 <legend>
	表单提交
 </legend>
	name:<input name="name" type="text"/><br/>
	file:<input type="file" name="file1"/><br/>
	<input type="submit" value="submit"/>		
</fieldset>
  </form>
 </body>
</html>

/**
 * Web.xml
 */
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.deepblue.web.UploadServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


图片:
注意:1、导入Io包。 2、在WebRoot下创建文件夹存储上传的文件。
  • 大小: 22.1 KB
  • 查看图片附件
发表评论
用户名: 匿名