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

求可以用的“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.*;