老师我这个没反应啊,你帮我看看
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>文件上传</h1>
<form action="${pageContext.request.contextPath}/UploadServlet" method="post" enctype="multipart/form-data">
<input type="text" name="name"><br/>
<input type="file" name="upload"><br/>
<input type="submit" value="上传">
</form>
</body>
</html>
package com.imooc.servlet;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory dis=new DiskFileItemFactory();
System.out.println("程序成功运行");
ServletFileUpload fileupload=new ServletFileUpload(dis);
try {
List<FileItem> list=fileupload.parseRequest(request);
for(FileItem fileItem:list){
if(fileItem.isFormField()){
String name=fileItem.getFieldName();
String value=fileItem.getString("UTF-8");
System.out.println(name+" "+value);
}else {
String fileName=fileItem.getName();
InputStream is=fileItem.getInputStream();
String path=getServletContext().getRealPath("/upload");
System.out.println(path);
OutputStream os=new FileOutputStream(path+"\\"+fileName);
int len=0;
byte[] b=new byte[1024];
while((len=is.read())!=-1){
os.write(b, 0, len);
}
is.close();
os.close();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星