在servlet中怎样上传文件?

在servlet中怎样上传文件?,第1张

//新建一个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)

}

上面就是了。。。。祝你好运哈!

其实你这个挡也显示图片其实很简单的,

你的需求无非是两个

1.servlet上传文件(图片)

2.点击 浏览 图标,然后选择图片文件,然后就可以在页面中的某个地方看到图片

是这两个需求么?

首先说第二个吧。

你上传图片之后,就马上触发js函数,内容为

var PicPath = document.getElementById("yourfile").value

document.getElementById("yourDiv").innerHTML="<IMG src="+PicPath+"/>"

OK了

第一个嘛就无所谓说了,不过我还是贴一个代码吧,

public void upLoadFile(HttpServletRequest request, HttpServletResponse response) {

PrintWriter out = null

response.setCharacterEncoding("UTF-8")

//实例化文件工厂

FileItemFactory factory = new DiskFileItemFactory()

//配置上传组件ServletFileUpload

ServletFileUpload upload = new ServletFileUpload(factory)

try {

out = response.getWriter()

//从request得到所有上传域的列表

List<FileItem>list = upload.parseRequest(request)

for (FileItem item : list) {

//isFormField判断一个item类对象封装的是一个普通的表单字段还是文件表单字段。

// 如果item是文件域,则做出如下处理:

if (!item.isFormField()) {

//上传文件域的Name

String fileName = item.getName()

//截取扩展名

int idx = fileName.lastIndexOf(".")

String extension = fileName.substring(idx)

//获取文件名

String name = new Date().getTime() + extension

//得到文件夹的物理路径

String path = this.getServletContext().getRealPath("\\upload")

//创建一个File

File file = new File(path + "\\" + name)

FileOutputStream o = new FileOutputStream(file)

InputStream in = item.getInputStream()

try {

LoadProcessServlet.process = 0

LoadProcessServlet.total = 100

LoadProcessServlet.isEnd = false

LoadProcessServlet.total = item.getSize()

byte b[] = new byte[1024]

int n

while ((n = in.read(b)) != -1) {

LoadProcessServlet.process+=n

o.write(b, 0, n)

System.out.println("实际:"+LoadProcessServlet.process)

}

} catch (Exception e) {

e.printStackTrace()

}finally{

LoadProcessServlet.isEnd = true

}

}

}

} catch (Exception e) {

e.printStackTrace()

}

}

上传:

需要导入两个包: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) {

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11534789.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-16
下一篇 2023-05-16

发表评论

登录后才能评论

评论列表(0条)

保存