⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileuploadbiz.java

📁 文件上传
💻 JAVA
字号:
package com.file.biz;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileuploadBiz {
	public boolean saveAs(HttpServletRequest request,String filepath)
	{
		
		DiskFileItemFactory factory = new DiskFileItemFactory();//创建基于磁盘的文件系统
		factory.setSizeThreshold(4096);//设置缓冲区大小
		
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(2*1024*1024);//设置最大上限的文件大小2M
		
		List fileList = null;
		try{
			fileList = upload.parseRequest(request);//获得需要上传的文件列表
			Iterator it = fileList.iterator();
			while(it.hasNext())
			{
				FileItem item = (FileItem)it.next();
				if(!item.isFormField())
				{
					String path = item.getName();
					if(path.length()==0)
						continue;
					if(item.getSize()>(2*1024*1024))
						System.out.println("文件超出2M");
					
					System.out.println(path);
					String[] temp = path.split("\\\\");
					String fullname = temp[temp.length-1];
					String srcname = fullname.substring(0,fullname.lastIndexOf("."));
					String kzm = fullname.substring(fullname.lastIndexOf("."),fullname.length());
					System.out.println(srcname);//文件名
					System.out.println(kzm);//扩展名
					//生成随即数
					Random rd = new Random();
					String newname = rd.nextInt(999999999)+"";
					File f = new File(filepath+newname+kzm);
					item.write(f);
					System.out.println("文件保存到"+filepath+fullname);
					
				}
				
			}
		      
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} 
	
		
		return true;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -