jsp+servlet 怎么实现文件上传

jsp+servlet 怎么实现文件上传,第1张

你要做文件上传吧 form表单里一定要设置这两个值enctype="multipart/form-data" method="post"

上传成功后会在tomcat里有那个文件 ,至于你说的要获取io流。那就需要找到那个文件给你写一下伪码吧:

//获得上传文件的路径

String path = getServletContext()getRealPath(webpath);

File file = new File(path);

filegetParentFile()mkdirs();

filecreateNewFile();

// 获得流

InputStream in = itemgetInputStream();

OutputStream out = new FileOutputStream(file);

不懂的再问我!

建议你用个上传组件,fileupload什么的

2、增加属性:ENCTYPE="multipart/form-data" 下面是一个用于上传文件的FORM表单的例子: <FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="/jspSmartUpload/uploadjsp"> <INPUT TYPE="FILE" NAME="MYFILE"> <INPUT TYPE="SUBMIT"> </FORM>二 上传的例子 1、上传页面uploadhtml 本页面提供表单,让用户选择要上传的文件,点击"上传"按钮执行上传操作。 页面源码如下: <!-- 文件名:uploadhtml 作 者:纵横软件制作中心雨亦奇(zhsoft88@sohucom) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 401 Transitional//EN"> <html> <head> <title>文件上传</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body> <p></p> <p align="center">上传文件选择</p> <FORM METHOD="POST" ACTION="jsp/do_uploadjsp" ENCTYPE="multipart/form-data"> <input type="hidden" name="TEST" value="good"> <table width="75%" border="1" align="center"> <tr> <td><div align="center">1、 <input type="FILE" name="FILE1" size="30"> </div></td> </tr> <tr> <td><div align="center">2、 <input type="FILE" name="FILE2" size="30"> </div></td> </tr> <tr> <td><div align="center">3、 <input type="FILE" name="FILE3" size="30"> </div></td> </tr> <tr> <td><div align="center">4、 <input type="FILE" name="FILE4" size="30"> </div></td> </tr> <tr> <td><div align="center"> <input type="submit" name="Submit" value="上传它!"> </div></td> </tr> </table> </FORM> </body> </html>2、上传处理页面do_uploadjsp 本页面执行文件上传操作。页面源码中详细介绍了上传方法的用法,在此不赘述了。 for (int i=0;i<sugetFiles()getCount();i++) { comjspsmartuploadFile file = sugetFiles()getFile(i); // 若文件不存在则继续 if (fileisMissing()) continue; // 显示当前文件信息 outprintln("<TABLE BORDER=1>"); outprintln("<TR><TD>表单项名(FieldName)</TD><TD>" + filegetFieldName() + "</TD></TR>"); outprintln("<TR><TD>文件长度(Size)</TD><TD>" + filegetSize() + "</TD></TR>"); outprintln("<TR><TD>文件名(FileName)</TD><TD>" + filegetFileName() + "</TD></TR>"); outprintln("<TR><TD>文件扩展名(FileExt)</TD><TD>" + filegetFileExt() + "</TD></TR>"); outprintln("<TR><TD>文件全名(FilePathName)</TD><TD>" + filegetFilePathName() + "</TD></TR>"); outprintln("</TABLE><BR>"); // 将文件另存 // filesaveAs("/upload/" + myFilegetFileName()); // 另存到以WEB应用程序的根目录为文件根目录的目录下 // filesaveAs("/upload/" + myFilegetFileName(), suSAVE_VIRTUAL); // 另存到操作系统的根目录为文件根目录的目录下 // filesaveAs("c:\\temp\\" + myFilegetFileName(), suSAVE_PHYSICAL); } %> </body> </html>(T007)

把要处理文件的程序封装成一个 类,然后把类放到 classes文件夹 里面以供 jsp页面调用 ,当然也可以写成servlet 在servlet里面调用 该处理文件的类,

还有不清楚的 加 QQ 540234292 详谈

public class MultipartTestServlet extends HttpServlet {

public MultipartTestServlet() { //构造方法

super();

}

public void doPost(HttpServletRequest request, HttpServletResponse response) //servlet的doPost方法处理POST请求

throws ServletException, IOException { //抛出异常

requestsetCharacterEncoding("gbk"); //设置字符为GBK

RequestContext requestContext = new ServletRequestContext(request); //实例化RequestContext对象

if(FileUploadisMultipartContent(requestContext)){

//判断是否包含 multipart 内容

DiskFileItemFactory factory = new DiskFileItemFactory();

// 创建基于磁盘的文件工厂

factorysetRepository(new File("c:/tmp/")); // 设置临时目录

ServletFileUpload upload = new ServletFileUpload(factory);

uploadsetHeaderEncoding("gbk");

uploadsetSizeMax(2000000); //设置缓冲区大小

List items = new ArrayList();

try {

items = uploadparseRequest(request); // 得到所有的文件

} catch (FileUploadException e1) {

Systemoutprintln("文件上传发生错误" + e1getMessage());

}

Iterator it = itemsiterator();

while(ithasNext()){

FileItem fileItem = (FileItem) itnext();

if(fileItemisFormField()){

Systemoutprintln(fileItemgetFieldName() + " " + fileItemgetName() + " " + new String(fileItemgetString()getBytes("iso8859-1"), "gbk")); //获得表单中域的名字。获得从浏览器中取得的文件全路径

}else{

Systemoutprintln(fileItemgetFieldName() + " " +

fileItemgetName() + " " +

fileItemisInMemory() + " " +

fileItemgetContentType() + " " +

fileItemgetSize());

if(fileItemgetName()!=null && fileItemgetSize()!=0){

// 浏览器中取得的文件全路径不为空 大小 不为0 则写入

File fullFile = new File(fileItemgetName());

File newFile = new File("c:/temp/" + fullFilegetName());

try {

fileItemwrite(newFile);

} catch (Exception e) {

eprintStackTrace();

}

}else{

Systemoutprintln("文件没有选择 或 文件内容为空");

}

}

}

}

}

}

上传:

需要导入两个包:commons-fileupload-121jar,commons-io-14jar

import javaioFile;

import javaioIOException;

import javautilList;

import javaxservletServletException;

import javaxservlethttpHttpServlet;

import javaxservlethttpHttpServletRequest;

import javaxservlethttpHttpServletResponse;

import orgapachecommonsfileuploadFileItem;

import orgapachecommonsfileuploaddiskDiskFileItemFactory;

import orgapachecommonsfileuploadservletServletFileUpload;

/

上传附件

@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 javaxservlethttpHttpServlet#doPost(javaxservlethttpHttpServletRequest, javaxservlethttpHttpServletResponse)

/

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

path = thisgetServletContext()getRealPath("/upload");

try {

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload up = new ServletFileUpload(factory);

List<FileItem> ls = upparseRequest(request);

for (FileItem fileItem : ls) {

if (fileItemisFormField()) {

String FieldName = fileItemgetFieldName();

//getName()返回的是文件名字 普通域没有文件 返回NULL

// String Name = fileItemgetName();

String Content = fileItemgetString("gbk");

requestsetAttribute(FieldName, Content);

} else {

String nm = fileItemgetName()substring(

fileItemgetName()lastIndexOf("\\") + 1);

File mkr = new File(path, nm);

if (mkrcreateNewFile()) {

fileItemwrite(mkr);//非常方便的方法

}

requestsetAttribute("result", "上传文件成功!");

}

}

} catch (Exception e) {

eprintStackTrace();

requestsetAttribute("result", "上传失败,请查找原因,重新再试!");

}

requestgetRequestDispatcher("/pages/admin/annex-managerjsp")forward(

request, response);

}

}

下载(i/o流)无需导包:

import javaioIOException;

import javanetURLEncoder;

import javaxservletServletException;

import javaxservlethttpHttpServlet;

import javaxservlethttpHttpServletRequest;

import javaxservlethttpHttpServletResponse;

/

下载文件

@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 javaxservlethttpHttpServlet#doPost(javaxservlethttpHttpServletRequest, javaxservlethttpHttpServletResponse)

/

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String name = requestgetParameter("fileName");

Systemoutprint("dddddddddd:" + name);

// web绝对路径

String path = requestgetSession()getServletContext()getRealPath("/");

String savePath = path + "upload";

// 设置为下载application/x-download

responsesetContentType("application/x-download");

// 即将下载的文件在服务器上的绝对路径

String filenamedownload = savePath + "/" + name;

// 下载文件时显示的文件保存名称

String filenamedisplay = name;

// 中文编码转换

filenamedisplay = URLEncoderencode(filenamedisplay, "UTF-8");

responseaddHeader("Content-Disposition", "attachment;filename="

+ filenamedisplay);

try {

javaioOutputStream os = responsegetOutputStream();

javaioFileInputStream fis = new javaioFileInputStream(

filenamedownload);

byte[] b = new byte[1024];

int i = 0;

while ((i = fisread(b)) > 0) {

oswrite(b, 0, i);

}

fisclose();

osflush();

osclose();

} catch (Exception e) {

}

}

}

你下载一个jspsmart组件,网上很容易下到,用法如下,这是我程序的相关片断,供你参考: <%@ page import="comjspsmartupload" %>

<jsp:useBean id="mySmartUpload" scope="page" class="comjspsmartuploadSmartUpload" />

<%

String photoname="photoname";

// Variables

int count=0; // Initialization

mySmartUploadinitialize(pageContext); // Upload

mySmartUploadupload();

for (int i=0;i<mySmartUploadgetFiles()getCount();i++){ // Retreive the current file

comjspsmartuploadFile myFile = mySmartUploadgetFiles()getFile(i); // Save it only if this file exists

if (!myFileisMissing()) {

javautilDate thedate=new javautilDate();

javatextDateFormat df = new javatextSimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

photoname = dfformat(thedate);

photoname +=""+ myFilegetFileExt();

myFilesaveAs("/docs/docimg/" + photoname);

count ++; } }

%>

<% String title="1";

String author="1";

String content="1";

String pdatetime="1";

String topic="1";

String imgintro="1";

String clkcount="1"; if(mySmartUploadgetRequest()getParameter("title")!=null){

title=(String)mySmartUploadgetRequest()getParameter("title");

title=new String(titlegetBytes("gbk"),"ISO-8859-1");

}

if(mySmartUploadgetRequest()getParameter("author")!=null){

author=(String)mySmartUploadgetRequest()getParameter("author");

author=new String(authorgetBytes("gbk"),"ISO-8859-1");

}

if(mySmartUploadgetRequest()getParameter("content")!=null){

content=(String)mySmartUploadgetRequest()getParameter("content");

content=new String(contentgetBytes("gbk"),"ISO-8859-1");

}

if(mySmartUploadgetRequest()getParameter("pdatetime")!=null){

pdatetime=(String)mySmartUploadgetRequest()getParameter("pdatetime");

}

if(mySmartUploadgetRequest()getParameter("topic")!=null){

topic=(String)mySmartUploadgetRequest()getParameter("topic");

}

if(mySmartUploadgetRequest()getParameter("imgintro")!=null){

imgintro=(String)mySmartUploadgetRequest()getParameter("imgintro");

imgintro=new String(imgintrogetBytes("gbk"),"ISO-8859-1");

}

if(mySmartUploadgetRequest()getParameter("clkcount")!=null){

clkcount=(String)mySmartUploadgetRequest()getParameter("clkcount");

}

//outprintln(code+name+birthday);

%>

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » jsp+servlet 怎么实现文件上传

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情