一》使用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"这样子的