io流文件上传,你会吗?

feitianmao 2012-07-24

写了个简陋的文件复制,其实我是想用IO流来实现文件上传的。我异想天开了,WEB上不是简单的复制。谁能教下怎么做,还有怎么处理文件复制过程文件丢失的问题。如果请我用fileupload这样的话就不用说了。看了下fileupload源码没找到流的处理过程。所以来这请教下
package com.fileupload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;

public class Copy {

/**
* @param args
*/
public static void main(String[] args) throws Exception {
File file1=new File("d:/工具包/AUTORUN.EXE");
File file2=new File("d:/hongbintest/io/io/io/");
/*System.out.print(file1.getName());
System.out.print(file2.toString());
System.out.print(file2.getName());*/
if(!file2.exists()){
file2.mkdirs();
}
copy(file1.toString(), file2.toString()+"/"+file1.getName());

}
    public static void copy(String file1,String file2) throws Exception{
   
    BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
        PrintStream ps=new PrintStream(new FileOutputStream(file2));
        String len;
        while((len=br.readLine())!=null){
        System.out.print(br.readLine());
            ps.println(len);
        }
br.close();
ps.flush();
ps.close();
    }
    public  static void copyfile(String s1,String s2) {
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(s1)));
            PrintStream ps=new PrintStream(new FileOutputStream(s2));
            String len;
            while((len=br.readLine())!=null){
                ps.println(len);
            }
            br.close();
            ps.flush();
            ps.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
hongyabing 2012-08-21

一》使用struts2中的封装类


1.使用strust2中的MultiPartRequestWrapper包装类来实现文件上传功能:


package com.file.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * 使用包装类MultiPartRequestWrapper来上传
 *
 */
public class MultiPartRequest extends ActionSupport {

   
    private static final long serialVersionUID = 1L;
    private static final String fileDIR = "/upload/";
    private HttpServletResponse response;
    /**
     * 包装MultiPartRequestWrapper实现文件上传功能
     *
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public String uploadFile() throws Exception {
        MultiPartRequestWrapper request = (MultiPartRequestWrapper) ServletActionContext
                .getRequest();
        Enumeration enu = request.getFileParameterNames();
        while (enu.hasMoreElements()) {
            // 获取文件参数名 即:<input type="file" name="attch"/>中的name名
            String controlName = (String) enu.nextElement();
            // 获取上传文件名
            String[] fileNames = request.getFileNames(controlName);
            // 获取上传文件的对象个数
            File[] uploadFiles = request.getFiles(controlName);
            // 创建要保存文件的文件夹
            File dir = new File(request.getRealPath("/") + "/" + fileDIR);
            if (!dir.exists())
                dir.mkdirs();
            for (int i = 0; i < uploadFiles.length; i++) {
                File saveFile = new File(request.getRealPath("/") + "/"
                        + fileDIR + fileNames[i]);
                // 获取上传文件的路径
                File uploadFile = uploadFiles[i];
                byte[] data = new byte[1024 * 6];
                int len = 0;
                BufferedInputStream bis = new BufferedInputStream(
                        new FileInputStream(uploadFile));
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(saveFile));
                while (-1 != (len = bis.read(data))) {
                    bos.write(data, 0, len);
                    bos.flush();
                }
                bos.close();
                bis.close();
            }
        }
        return "input";
    }
   
    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }
}



二》使用stuts2中的自带的上传功能:

1.代码如下:

package com.file.upload;

import java.io.File;

import org.apache.commons.io.FileUtils;

import com.common.BaseAction;
import com.opensymphony.xwork2.Preparable;

/**
 * Struts2上传文件的简介版本
 *
 */
public class S2UploadFile extends ActionSupport{

    private static final long serialVersionUID = 1L;

    // 上传文件,这个文件名必须和页面中的上传文件筐中的name值必须一致
    // 文件名,文件类型的命名必须是 文件的名字+文件名,文件类型 即:upload+FileName,upload+ContentType
    private File[] upload;
    // 上传文件名
    private String [] uploadFileName;
    // 上传文件类型
    private String uploadContentType;
    // 文件存放路径
    private String root_path;

    /**
     * 上传文件
     *
     * @return String
     * @throws Exception
     */
    public String uploadFile() throws Exception {
        root_path = request.getSession().getServletContext().getRealPath("/");
        if (null == uploadFileName)
            return "error";
        for (int i = 0; i < upload.length; i++) {
            File saveFile = new File(root_path + "/upload/" + uploadFileName[i]);
            if (!saveFile.exists()) {
                //创建父路径后,在创建文件
                saveFile.getParentFile().mkdirs();
                saveFile.createNewFile();
            }
            FileUtils.copyFile(upload[i], saveFile);
        }
        return "success";
    }

    public File[] getUpload() {
        return upload;
    }

    public void setUpload(File[] upload) {
        this.upload = upload;
    }

    public String[] getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String[] uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String getRoot_path() {
        return root_path;
    }

    public void setRoot_path(String rootPath) {
        root_path = rootPath;
    }

}

三》使用Java中的IO流来上传(不推荐)使用

package com.file.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通过流的形式来上传(不建议使用该种方法)
 *
 *
 */
public class UpLoadFile extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
//        this.doPost(request, response);
    }

    @SuppressWarnings("deprecation")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            // 文件路徑
            String path = (new String(request.getParameter("path").getBytes(
                    "ISO-8859-1"), "UTF-8")).replaceAll("\\\\", "\\\\\\\\");
            // 文件名
            String fileName = path.substring(path.lastIndexOf("\\") + 1, path
                    .length());
            String rootPath = request.getRealPath("/");
            File file = new File(rootPath + "/" + "upload");
            if (!file.exists())
                file.mkdirs();
            fis = new FileInputStream(path);
            fos = new FileOutputStream(request.getRealPath("/upload") +"\\"+ fileName);
            int len = 0;
            byte[] buff = new byte[1024];
            while (-1 != (len = fis.read(buff))) {
                fos.write(buff, 0, len);
                fos.flush();
            }
            response.getWriter().write("success!");
        } catch (IOException e) {
            System.out.println(e.toString());
            try {
                response.getWriter().write("fail!");
            } catch (IOException e1) {
                System.out.println(e1.toString());
            }
        } finally {
                try {
                    if (null != fos)
                    fos.close();
                } catch (IOException e) {
                    System.out.println("fos close:"+e.toString());
                }
                try {
                    if (null != fis)
                    fis.close();
                } catch (IOException e) {
                    System.out.println("fis close:"+e.toString());
                }
        }
    }

}

四》  上面的工程使用的包如下:

commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging.jar
freemarker-2.3.15.jar
struts2-core-2.1.8.1.jar
xwork-core-2.1.6.jar


五》 页面中的表单如下:

<form name="UploadForm" enctype="multipart/form-data" method="post"></form>

表单必须是enctype="multipart/form-data"这样子的


bing_zz 2012-08-22
web上传文件,像from enctype="multipart/form-data"不都是传IO流的吗?难道能是什么其他的东西?
验证文件复制过程是否损坏,可以验证MD5码。
Global site tag (gtag.js) - Google Analytics