java怎么上传文件,图片呢

解决方案 »

  1.   


    String temp=request.getSession().getServletContext().getRealPath("/")+"temp"; //临时目录 
    String loadpath=request.getSession().getServletContext().getRealPath("/")+"Image"; //上传文件存放目录
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(1*1024*1024); // 设置允许用户上传文件大小,单位:字节 
    fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节 
    fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 //开始读取上传信息 
    int index=0;
    List fileItems = fu.parseRequest(request);
    Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
    while (iter.hasNext())
    {
    FileItem item = (FileItem)iter.next();// 忽略其他不是文件域的所有表单信息
    if (!item.isFormField())
    {
    String name = item.getName();//获取上传文件名,包括路径
    name=name.substring(name.lastIndexOf("\\")+1);//从全路径中提取文件名
    long size = item.getSize();
    if((name==null||name.equals("")) && size==0) 
    continue; 
    int point = name.indexOf(".");
    name=(new Date()).getTime()+name.substring(point,name.length())+index;
    index++;
    File fNew= new File(loadpath, name);
    item.write(fNew);
    }
    else //取出不是文件域的所有表单信息
    {
    String fieldvalue = item.getString();
    //如果包含中文应写为:(转为UTF-8编码)
    //String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
    }
    }
      

  2.   


    String temp=request.getSession().getServletContext().getRealPath("/")+"temp"; //临时目录 
    String loadpath=request.getSession().getServletContext().getRealPath("/")+"Image"; //上传文件存放目录
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(1*1024*1024); // 设置允许用户上传文件大小,单位:字节 
    fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节 
    fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 //开始读取上传信息 
    int index=0;
    List fileItems = fu.parseRequest(request);
    Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
    while (iter.hasNext())
    {
    FileItem item = (FileItem)iter.next();// 忽略其他不是文件域的所有表单信息
    if (!item.isFormField())
    {
    String name = item.getName();//获取上传文件名,包括路径
    name=name.substring(name.lastIndexOf("\\")+1);//从全路径中提取文件名
    long size = item.getSize();
    if((name==null||name.equals("")) && size==0) 
    continue; 
    int point = name.indexOf(".");
    name=(new Date()).getTime()+name.substring(point,name.length())+index;
    index++;
    File fNew= new File(loadpath, name);
    item.write(fNew);
    }
    else //取出不是文件域的所有表单信息
    {
    String fieldvalue = item.getString();
    //如果包含中文应写为:(转为UTF-8编码)
    //String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
    }
    }
      

  3.   

    我也来个/**
     * 
     */
    package cn.demo.fupload;import java.io.File;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    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 org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;/**
     * @author Administrator
     * @version 2009-3-8 文件的上传下载commons-fileupload
     */
    public class FileUploadServlet extends HttpServlet { /**
     * 
     */
    private static final long serialVersionUID = 1068590804829697704L;
    private ServletContext sc;//获取设备上下文对象
    private String savePath;//保存的路径
    /**
     * @param args
     * @throws UnsupportedEncodingException 
     */
    public void doGet(HttpServletRequest request,HttpServletResponse response)
    throws UnsupportedEncodingException,ServletException,IOException{
    doPost(request,response);
    //将get请求和post请求统一发送给doPost处理
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response)
    throws UnsupportedEncodingException,ServletException,IOException{
    //设置编码格式
    request.setCharacterEncoding("GBK");
    //使用FileItemFactory创建新的文件项目 
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //FileUpload用来解析request文件上传请求
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
    //获取请求的信息存入列表list中
    List tempList = upload.parseRequest(request); Iterator it = tempList.iterator();
    while(it.hasNext()){
    FileItem item = (FileItem)it.next();
    //判断items中的文本信息
    if(item.isFormField()){
    System.out.println("表单参数的名称"+item.getFieldName()
    +"表单的参数值"+item.getString("GBK"));
    }else{
    if(item.getName()!=null&&!item.getName().equals("")){
    System.out.println("所上传的文件名称:"+item.getName());
    System.out.println("所上传的文件大小:"+item.getSize());
    System.out.println("所上传的文件类别:"+item.getContentType());
    //用于获取file中的文件名(不包含路径)
    File tempFile = new File(item.getName());
    //建立文件内容
    File file = new File(sc.getRealPath("/")+savePath,tempFile.getName());
    //将文件上传至服务器
    item.write(file);
    request.setAttribute("upload.message", "上传文件成功!"+item.getName()+item.getSize()+item.getContentType());
    }else{
    request.setAttribute("upload.message", "没有选择文件!");
    }//end else 
    }//end else
    }//end while
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println("上传文件失败!");
    request.setAttribute("upload.message"," 上传文件失败!");
    }
    request.getRequestDispatcher("../uploadResult.jsp").forward(request,  response);
    }
    public void init(ServletConfig config){
    //获取配置文件保存的变量值
    savePath = config.getInitParameter("savePath");
    //获取Servlet上下文对象
    sc = config.getServletContext();
    }
    }
      

  4.   

    文件上传在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件上传功能。common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载。用该组件可实现一次上传一个或多个文件,并可限制文件大小。
    下载后解压zip包,将commons-fileupload-1.0.jar复制到tomcat的webapps\你的webapp\WEB-INF\lib\下,目录不存在请自建目录。
      

  5.   

    <xml version="1.0" encoding="ISO-8859-1"?>       PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"    
        "http://java.sun.com/dtd/web-app_2_3.dtd">   
       
    <web-app>   
        <servlet>   
            <servlet-name>Uploadservlet-name>   
            <servlet-class>Uploadservlet-class>   
       </ servlet>   
       
        <servlet-mapping>   
            <servlet-name>Uploadservlet-name>   
            <url-pattern>/fileuploadurl-pattern>   
       </ servlet-mapping>   
    <web-app>  
      

  6.   

    用struts2 ,很简单的,就几行代码!public String upheadimg(){
    if(headimg!=null && headimg.isFile()){
    ServletContext application=ServletActionContext.getServletContext();
    String path=application.getRealPath("/upload");
    File dir = new File(path);
    if (!dir.exists() || !dir.isDirectory()) {
    dir.mkdirs();
    } String filename=UUID.randomUUID()+headimgFileName.substring(headimgFileName.lastIndexOf("."));
    try {
    FileUtils.copyFile(headimg, new File(path +"/"+filename));
    headName="/99Accountbook/upload/"+filename;
    System.out.println("上传头像成功");
    //ActionContext.getContext().put("headimg", "/99Accountbook/upload/"+filename);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    return "success";
    }