uploadfileaction.java

来自「电子商务网站使用MVC模式B/S结构功能不是很全适合初学者看」· Java 代码 · 共 73 行

JAVA
73
字号
package Administrator;
import java.text.SimpleDateFormat;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javazoom.upload.*;

public class uploadfileAction extends HttpServlet{
	public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
		request.setCharacterEncoding("GBK");//设置编码格式,就不用一个个转码了。 
		javazoom.upload.UploadBean upBean = new UploadBean(); 
		javazoom.upload.MultipartFormDataRequest mrequest = null; 
		Hashtable files = null; 
		try{
			if (MultipartFormDataRequest.isMultipartFormData(request)) { 
				mrequest = new MultipartFormDataRequest(request,null,100*1024*1024,MultipartFormDataRequest.COSPARSER,"GBK");//注意这里也要设置编码参数 
				String card = mrequest.getParameter("card"); 
				System.out.println("<br>Title0是:"+card+"<br>"); 
				String sTt1 = new String(card.getBytes("ISO-8859-1"),"GBK"); 
				System.out.println("<br>Title1是:"+sTt1+"<br>"); 
				//这里用来测试title参数是否正确。调试的时候,加一句if (true)return;即可。 
				files = mrequest.getFiles(); 
			}
		}catch(Exception e){
			System.out.println(e.getMessage());
			
		}	 
		
		//获取修改前的文件名 
		String sOldFileName =mrequest.getParameter("oldfilename"); 
		System.out.println("sOldFileName:"+sOldFileName); 
		String sWebRootPath = request.getRealPath("/");//得到你的web应用的根。 
		String sPath=sWebRootPath+"attach"; 
		int iFileCount = 0; 
		String sServerFileName=""; 
		String sLocalFileName = ""; 
		//文件获取 
		if ( (files != null) || (!files.isEmpty()) ) { 
			iFileCount = files.size(); 
			UploadFile file = (UploadFile) files.get("attach"); 
			sLocalFileName=file.getFileName(); 
			System.out.println("sLocalFileName:"+sLocalFileName); 
			int ii= sLocalFileName.indexOf("."); //取文件名的后缀 
			String sExt = sLocalFileName.substring(ii,sLocalFileName.length()); 
			//得到不重复的文件名 
			java.util.Date dt = new java.util.Date(System.currentTimeMillis()); 
			SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); 
			sServerFileName= fmt.format(dt); 
			sServerFileName =sServerFileName + sExt; 
			//如果不存在该目录,则新建一个 
			File dir =new File(sPath); 
			if (!dir.exists()){ 
				dir.mkdirs(); 
			}
			try{
				upBean.setFolderstore(sPath);//设置要上传的目录 
				upBean.store(mrequest, "attach");//上传 
				System.out.println("file path is "+sPath+"/"+sServerFileName);
			}catch(Exception e){
				System.out.println(e.getMessage());
			}
			 
		} 
	}	
	public void doPost(HttpServletRequest request,HttpServletResponse response)
	   throws IOException,ServletException
	   {
	   	doGet(request,response);
	   }
} 

⌨️ 快捷键说明

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