今天有个朋友问到上传文件 以前这方面都交给韦锴做了 因为群里朋友代码有错 所以 我就自己google了下 改了改代码 搞定
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.yak.struts.action;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import com.yak.struts.form.TestForm;
/**
* MyEclipse Struts Creation date: 06-30-2008
*
* XDoclet definition:
*
* @struts.action path="/test" name="testForm" input="/form/test.jsp"
* parameter="status" scope="request" validate="true"
*/
public class TestAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
TestForm testForm = (TestForm) form;// TODO Auto-generated method stub
FormFile ff = testForm.getFile();
String fname = ff.getFileName();
System.out.println("fileName======>" + fname);
if (ff.getFileName() != null && ff.getFileSize() != 0) {
File newFile = new File("D:/java/newdata/2003-04-14/" + fname);
System.out.println(newFile + "======>" + fname);
try {
if (!(new File("D:/java/newdata/").isDirectory())) {
new File("D:/java/newdata/").mkdir();
new File("D:/java/newdata/2003-04-14/").mkdir();
} else {
new File("D:/java/newdata/2003-04-14/").mkdir();
}
} catch (SecurityException e) {
System.out.println("can not make directory");
}
try {
int size = ff.getFileSize();
System.out.println("size=======>" + size);
byte[] data = new byte[size];
ff.getInputStream().read(data);
try {
FileOutputStream fos = new FileOutputStream(newFile);
// 用fos.write("你要写入的内容");
fos.write(data);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}