求可以用的“jsp上传文件”代码
废话不用说,直接给我代码,必须要能够用的,有注释就更好
[解决办法]
jsp上传文件的代码?
<input type="file" name="file" />
备注:form 中加上这段代码enctype="multipart/form-data"
<form action="" name="" enctype="multipart/form-data">
</form>
[解决办法]
jsp页面: <form action="UploadServlet" method="post" enctype="multipart/form-data">
username: <input type="text" name="username"><br>
file: <input type="file" name="file"><br>
file2: <input type="file" name="file2"><br>
<input type="submit" value="submit">
</form>
后台servlet:
public class UploadServlet extends HttpServlet
{
@SuppressWarnings( {"unchecked", "deprecation"})
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
DiskFileItemFactory factory = new DiskFileItemFactory();
String path = req.getRealPath("/upload");
factory.setRepository(new File(path));
factory.setSizeThreshold(1024 * 1024);
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List<FileItem> list = (List<FileItem>)upload.parseRequest(req);
for (FileItem item : list)
{
String name = item.getFieldName();
if (item.isFormField())
{
String value = item.getString();
System.out.println(name + "=" + value);
req.setAttribute(name, value);
}
else
{
String value = item.getName();
int start = value.lastIndexOf("\\");
String fileName = value.substring(start + 1);
req.setAttribute(name, fileName);
item.write(new File(path, fileName));
//
//OutputStream os = new FileOutputStream(new File(path, fileName));
//
//InputStream is = item.getInputStream();
//
//byte[] buffer = new byte[400];
//
//int length = 0;
//
//while((length = is.read(buffer)) != -1)
//{
//os.write(buffer, 0, length);
//}
//
//is.close();
//os.close();
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
req.getRequestDispatcher("fileUploadResult.jsp").forward(req, resp);
}
}
[解决办法]
package tom.jiafei;
import java.io.*;
import javax.servlet.http.*;
public class UpFile{
HttpServletRequest request;
HttpSession session;
String upFileMessage="";
public void setRequest( HttpServletRequest request){
this.request=request;
}
public void setSession( HttpSession session){
this.session=session;
}
public String getUpFileMessage(){
String fileName=null;
try{String tempFileName=(String)session.getId();
File f1=new File("C:/2011xinxi/download",tempFileName);
FileOutputStream o=new FileOutputStream(f1);
InputStream in=request.getInputStream();
byte b[]=new byte[10000];
int n;
while((n=in.read(b))!=-1){
o.write(b,0,n);
}
o.close();
in.close();
RandomAccessFile random =new RandomAccessFile(f1,"r");
int second=1;
String secondLine=null;
while(second<=2){
secondLine=random.readLine();
second++;
}
int position=secondLine.lastIndexOf('\\');
fileName=secondLine.substring(position+1,secondLine.length()-1);
byte cc[]=fileName.getBytes("ISO-8859-1");
fileName=new String(cc);
session.setAttribute("Name",fileName);
random.seek(0);
long forthEndPosition=0;
int forth=1;
while((n=random.readByte())!=-1&&forth<=4){
if(n=='\n'){
forthEndPosition=random.getFilePointer();
forth++;
}
}
File f2=new File("C:/2011xinxi/download",fileName);
RandomAccessFile random2 =new RandomAccessFile(f2,"rw");
random.seek(random.length());
long endPosition=random.getFilePointer();
long mark= endPosition;
int j=1;
while((mark>=0)&&(j<=6))
{mark--;
random.seek(mark);
n=random.readByte();
if(n=='\n'){
endPosition=random.getFilePointer();
j++;
}
}
random.seek(forthEndPosition);
long startPoint=random.getFilePointer();
while(startPoint<endPosition-1){
n=random.readByte();
random2.write(n);
startPoint=random.getFilePointer();
}
random2.close();
random.close();
f1.delete();
upFileMessage=fileName+" Successfully Upload";
return upFileMessage;
}
catch( Exception exp){
if(fileName!=null){upFileMessage=fileName+"Fail to Upload";
return upFileMessage;}
else{upFileMessage="";
return upFileMessage;
}
}
}}
我刚做的实验
[解决办法]
example5_9.jsp
<%@ page contentType="text/html;charset=gb2312"%><html> <body> <p>选择要上传的文件:<br> <form action="accept.jsp" method="post" enctype="multipart/form-data"> <input type="FILE" name="boy" size="38"> <br><input type="submit" name="g" value="提交"> </form> </body></html>
[解决办法]
<input type="submit" value="提交">
</form>
</body>
</html>
doUpload.jsp
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<html><head><title>upFile</title></head>
<body bgcolor="#ffffff">
<%
//定义上载文件的最大字节
int MAX_SIZE = 102400 * 102400;
// 创建根路径的保存变量
String rootPath;
//声明文件读入类
DataInputStream in = null;
FileOutputStream fileOut = null;
//取得客户端的网络地址
String remoteAddr = request.getRemoteAddr();
//获得服务器的名字
String serverName = request.getServerName();
//取得互联网程序的绝对地址
String realPath = request.getRealPath(serverName);
realPath = realPath.substring(0,realPath.lastIndexOf("\\"));
//创建文件的保存目录
rootPath = realPath + "\\upload\\";
//取得客户端上传的数据类型
String contentType = request.getContentType();
try{
if(contentType.indexOf("multipart/form-data") >= 0){
//读入上传的数据
in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
if(formDataLength > MAX_SIZE){
out.println("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>");
return;
}
//保存上传文件的数据
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
//上传的数据保存在byte数组
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes,totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
//根据byte数组创建字符串
String file = new String(dataBytes);
//out.println(file);
//取得上传的数据的文件名
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
//取得数据的分隔字符串
String boundary = contentType.substring(lastIndex + 1,contentType.length());
//创建保存路径的文件名
String fileName = rootPath + saveFile;
//out.print(fileName);
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
int boundaryLocation = file.indexOf(boundary,pos) - 4;
//out.println(boundaryLocation);
//取得文件数据的开始的位置
int startPos = ((file.substring(0,pos)).getBytes()).length;
//out.println(startPos);
//取得文件数据的结束的位置
int endPos = ((file.substring(0,boundaryLocation)).getBytes()).length;
//out.println(endPos);
//检查上载文件是否存在
File checkFile = new File(fileName);
if(checkFile.exists()){
out.println("<p>" + saveFile + "文件已经存在.</p>");
}
//检查上载文件的目录是否存在
File fileDir = new File(rootPath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
//创建文件的写出类
fileOut = new FileOutputStream(fileName);
//保存文件的数据
fileOut.write(dataBytes,startPos,(endPos - startPos));
fileOut.close();
out.println(saveFile + "文件成功上载.</p>");
}else{
String content = request.getContentType();
out.println("<p>上传的数据类型不是multipart/form-data</p>");
}
}catch(Exception ex){
throw new ServletException(ex.getMessage());
}
%>
</body>
</html>
运行方法,将这两个JSP文件放在同一路径下,运行UploadExample.jsp即可。
[解决办法]