日期:2014-05-18  浏览次数:20804 次

如何用org.apache.commons.fileupload上传文件呢?
给个例子吧

------解决方案--------------------
public class Upload {
private static long lastTime;
private static int n;
public static synchronized String getNo(){
long time=System.currentTimeMillis();
if(time==lastTime){
return time+ "_ "+n++;
}else{
n=0;
lastTime=time;
return time+ "_ "+n;
}

}
private List <FileItem> files=new ArrayList <FileItem> ();
private HashMap <String,String> parameters=new HashMap <String,String> ();
public Upload(HttpServletRequest request) throws FileUploadException{
DiskFileUpload fu = new DiskFileUpload();
fu.setHeaderEncoding( "gb2312 ");
fu.setSizeMax(200000000);
fu.setSizeThreshold(4096);
List fileItems = fu.parseRequest(request);
int length=fileItems.size();
for(int i=0;i <length;i++){
FileItem fi=(FileItem)fileItems.get(i);
if (fi.isFormField()) {
String name = fi.getFieldName();
String value = fi.getString();
parameters.put(name,value);

}else{
files.add(fi);
}

}


}
public Accessory saveFile(FileItem fi) throws Exception{
if(fi.getName()==null||fi.getName().equals( " ")) return null;
String name=null;
String fileName = fi.getName();
name = fileName.substring(fileName.lastIndexOf( "\\ ") + 1 , fileName.length());

String temp=Upload.getNo();
String type=fileName.substring(fileName.lastIndexOf( ". "));
String tempName=temp+type;

File file=new File( "D:/temp/ "+tempName);
// File parent=file.getParentFile();
// if(!parent.exists())parent.mkdirs();
fi.write(file);

Accessory accessory=new Accessory();
accessory.setName(name);
accessory.setTempName(tempName);
accessory.setPath( "D:/temp/ ");

return accessory;

}
public static String toUtf8String(String s) {
StringBuffer sb = new StringBuffer();
for (int i=0;i <s.length();i++) {
char c = s.charAt(i);
if (c > = 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes( "utf-8 ");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) k += 256;
sb.append( "% " + Integer.toHexString(k).
toUpperCase());
}
}
}
return sb.toString();
}
public Accessory saveFile(FileItem fi,String filePath) throws Exception{

File rootPathFileDir = new File(filePath);
if (rootPathFileDir.length() == 0 && !rootPathFileDir.isDirectory()){
rootPathFileDir.mkdirs();
} else if (!rootPathFileDir.isDirectory()){
rootPathFileDir.mkdirs();
}
filePath = rootPathFileDir.getPath();
filePath = filePath.replaceAll( "\\\\ ", "/ ");
System.out.println(rootPathFileDir.getPath());

String name=null;
String fileName = fi.getName();
name = fileName.substring(fileName.lastIndexOf( "\\ ") + 1 , fileName.length());

String temp=Upload.getNo();
String type=fileName.substring(fileName.lastIndexO