如何获取file 文件上传是的参数
发布网友
发布时间:2022-04-25 08:17
我来回答
共1个回答
热心网友
时间:2022-04-23 03:29
package servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class upload extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 2654821751525075943L;
private ServletContext sc;
private String savePath;
/**
* 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);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username="";
request.setCharacterEncoding("utf-8");
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);//专门用来完成文件上传的类
try {
List items=upload.parseRequest(request);//解析请求,返回一个存储了所有表单元素的集合
Iterator it=items.iterator();
while(it.hasNext()){
FileItem item=(FileItem)it.next();
if(item.isFormField()){//如果是普通的文本信息,返回true
username=item.getString("utf-8");
}else{
if(item.getName()!=null&&!item.getName().equals("")){//防止抛出空指针,判断一下是否为空
System.out.println("上传文件的大小:"+item.getSize());
System.out.println("上传文件的类型:"+item.getContentType());
System.out.println("上传文件的名称:"+item.getName());
File temp=new File(item.getName());
File file=new File(sc.getRealPath("/")+savePath,temp.getName());
item.write(file);
HttpSession hs=request.getSession();
hs.setAttribute("path", item.getName());
request.setAttribute("msg", "上传文件成功了");
}else{
request.setAttribute("msg", "上传文件失败了");
}
}
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("msg", "上传文件失败了");
}
request.getRequestDispatcher("/result.jsp?username="+username).forward(request, response);
}
/**
* 重写init方法
*/
public void init(ServletConfig config){
savePath=config.getInitParameter("savePath");//获取初始化的参数
sc=config.getServletContext();//获取ServletContext对象,并赋给sc
}
}