日期:2014-05-17  浏览次数:20779 次

求使用FileUpload来上传文件的可用代码
要上传的文件名是从一个页面传过来的file_name值
该表单代码如下:
<FORM METHOD="POST" ACTION="upload_result.jsp" ENCTYPE="multipart/form-data">
<INPUT TYPE="FILE" name="file_name" SIZE="50"><BR>
<INPUT TYPE="SUBMIT" VALUE="Upload">
</FORM>

如何将该文件保存到我本地的某个路径下呢?
请大家提供可用的JSP或者Servlet代码,非常感谢!

注意,我没有用STRUTS等框架,希望能用COMMONS FILEUPLOAD解决上传问题

------解决方案--------------------

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());
}

------解决方案--------------------
Java code
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