日期:2014-05-17 浏览次数:20879 次
String username=""; SmartUpload mySmartUpload =new SmartUpload(); long file_size_max=5242880; //文件大小 String fileName2="",ext="",testvar=""; String url="selfimages/"; //应保证在根目录中有此目录的存在(也就是说需要自己建立相应的文件夹) //初始化 mySmartUpload.initialize(pageContext); //只允许上载此类文件 try { //上载文件 mySmartUpload.upload(); if(mySmartUpload.getRequest().getParameter("username")==null) { out.print("<script>alert('操作有误,请重新操作!');history.go(-1);</script>"); return; } username=mySmartUpload.getRequest().getParameter("username"); } catch(Exception e) {} try { com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0); if (myFile.isMissing()){out.println("Missing");} else { ext= myFile.getFileExt(); //取得后缀名 int file_size=myFile.getSize(); //取得文件的大小 String saveurl=""; if(file_size<file_size_max) { saveurl=application.getRealPath("/")+url; saveurl+=username+".*** "; //上传文件的后缀名(***改成自己要的文件后缀) myFile.saveAs(saveurl,SmartUpload.SAVE_PHYSICAL); out.println("<script>document.location.href = '*****.jsp;'</script>"); } } } catch (Exception e) { out.print(e.toString()); }
------解决方案--------------------
首先把fileupload的jar包导入进去,
步骤:
1.创建一个Servlet----Upload.java文件,用于实现上传文件
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
public class Upload extends HttpServlet {
private String uploadPath = "d:\\upload\\"; // 上传文件的目录
private String tempPath = "d:\\upload\\tmp\\"; // 临时文件目录
在doPost()方法中,当ser