需要导入两个包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
import java.io.File
import java.io.IOException
import java.util.List
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.apache.commons.fileupload.FileItem
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import org.apache.commons.fileupload.servlet.ServletFileUpload
/**
* 上传附件
* @author new
*
*/
public class UploadAnnexServlet extends HttpServlet {
private static String path = ""
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response)
}
/*
* post处理
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
path = this.getServletContext().getRealPath("/upload")
try {
DiskFileItemFactory factory = new DiskFileItemFactory()
ServletFileUpload up = new ServletFileUpload(factory)
List<FileItem>ls = up.parseRequest(request)
for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName = fileItem.getFieldName()
//getName()返回的是文件名字 普通域没有文件 返回NULL
//String Name = fileItem.getName()
String Content = fileItem.getString("gbk")
request.setAttribute(FieldName, Content)
} else {
String nm = fileItem.getName().substring(
fileItem.getName().lastIndexOf("\\") + 1)
File mkr = new File(path, nm)
if (mkr.createNewFile()) {
fileItem.write(mkr)//非常方便的方法
}
request.setAttribute("result", "上传文件成功!")
}
}
} catch (Exception e) {
e.printStackTrace()
request.setAttribute("result", "上传失败,请查找原因,重新再试!")
}
request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(
request, response)
}
}
下载(i/o流)无需导包:
import java.io.IOException
import java.net.URLEncoder
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* 下载文件
* @author
*
*/
public class DownloadFilesServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8594448765428224944L
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response)
}
/*
* 处理请求
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("fileName")
System.out.print("dddddddddd:" + name)
// web绝对路径
String path = request.getSession().getServletContext().getRealPath("/")
String savePath = path + "upload"
// 设置为下载application/x-download
response.setContentType("application/x-download")
// 即将下载的文件在服务器上的绝对路径
String filenamedownload = savePath + "/" + name
// 下载文件时显示的文件保存名称
String filenamedisplay = name
// 中文编码转换
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8")
response.addHeader("Content-Disposition", "attachmentfilename="
+ filenamedisplay)
try {
java.io.OutputStream os = response.getOutputStream()
java.io.FileInputStream fis = new java.io.FileInputStream(
filenamedownload)
byte[] b = new byte[1024]
int i = 0
while ((i = fis.read(b)) >0) {
os.write(b, 0, i)
}
fis.close()
os.flush()
os.close()
} catch (Exception e) {
}
}
}
//新建一个Smartupload对象SmartUpload
su=new
SmartUpload()
//上传初始化
su.initialize(pageContext)
//设定上传限度
//1.限定每个上传文件的最大长度
//su.setMaxFileSize(100000)
//2.限制总上传数据的长度。
//su.setTotalMaxFileSize(20000)
//3.设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。
//su.setAllowFilesList("doc,text")
//4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html扩展名的文件或没有扩展名的文件
//su.setDeniedDilesList("exe,bat,jsp,html,htm,,")
//上传文件
su.upload()
//将上传文件全部保存到指定目录
int
count=su.save("/upload")
out.println(count+"个上传文件成功!<br>")
//利用Request对象获取参数之值
out.println("test="+su.getRequest().getParameter("test")+"<br><br>")
//逐一提取上传文件信息,同时可保存文件。
for(int
i=0i<su.getFiles().getCount()i++)
{
com.jspsmart.upload.File
file=su.getFiles().getFile(i)
//若文件不存在则继续
if(file.isMissing())
continue
//显示当前文件信息
out.println("<table
border=1>")
out.println("<tr><td>表单项名(FiledName)</td><td>"+file.getFieldName()+"</tr></tr>")
out.println("<tr><td>文件长度(Size)</td><td>"+file.getSize()+"</td><td>")
out.println("<tr><td>文件名(FileName)</td><td>"+file.getFileName()+"</tr></tr>")
out.println("<tr><td>文件扩展名(FiledExt)</td><td>"+file.getFileExt()+"</tr></tr>")
out.println("<tr><td>文件全名(FiledPathName)</td><td>"+file.getFilePathName()+"</tr></tr>")
out.println("</table><br>")
//将文件另存
//file.saveAs("/upload/"+myFile.getFileName())
//另存到以web应用程序的根目录为文件根目录的目录下
//file.saveAs("/upload/"+myFile.getFileName(),su.SAVE_VIRTUAL)
//另存到 *** 作系统的根目录为文件根目录的目录下
//file.safeAs("c://temp//"+myFile.getFileName(),su.SAVE_PHYSICAL)
}
上面就是了。。。。祝你好运哈!
import java.io.IOExceptionimport java.io.PrintWriter
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import com.jspsmart.upload.*
import net.sf.json.JSONObject
import action.StudentAction
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response)
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean result=true
SmartUpload mySmartUpload=new SmartUpload()
mySmartUpload.initialize(this.getServletConfig(), request,response)
mySmartUpload.setTotalMaxFileSize(50*1024*1024)//大小限制
mySmartUpload.setAllowedFilesList("doc,docx")//后缀名限制
try {
mySmartUpload.upload()
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0)
myFile.saveAs("/file/"+1+".doc")//保存目录
} catch (SmartUploadException e) {
e.printStackTrace()result=false
}
//*****************************//
response.setContentType("text/htmlcharset=UTF-8")
response.setHeader("Cache-Control","no-cache")
PrintWriter out = response.getWriter()
out.print(result)
out.flush()
out.close()
}
}
//我这是ajax方式的,不想这样,把//**********************//以下部分修改就行了
//需要SmartUpload组件,去网上下个就行了,也有介绍的
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)