小白求指教,现在只能改个首页而已,然后登个首页而已(๑• . •๑)
遇到了同样的问题,在CSDN看到了,希望阿里云团队能够给出正确、标准的答案~请查看
简介: 导包 commons-fileupload-1.3.1.jar commons-io-2.2.jar import java.io.File; import java.io.FileOutputStream; import java. 导包 commons-fileupload-1.3.1.jar commons-io-2.2.jar
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadHandleServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String savePath=this.getServletContext().getRealPath("/WEB-INF/upload/");
File file=new File(savePath);
if(!file.exists()&&!file.isDirectory()){
System.out.println(savePath+"目录不存在,需要创建");
//创建目录
file.mkdirs();
}
//消息提示
String message="";
//创建DiskFileItemFactory工厂
DiskFileItemFactory factory=new DiskFileItemFactory();
//创建一个文件上传解析器
ServletFileUpload upload=new ServletFileUpload(factory);
//解决文件上传乱码问题
upload.setHeaderEncoding("UTF-8");
if(!ServletFileUpload.isMultipartContent(request)){
//按照传统方面获取数据
return;
}
try {
//使用ServletFileUpload解析器解析数据,返回来的是一个List<FileItem>集合,每一个FileItem对应一个表单输出
List<FileItem> list=upload.parseRequest(request);
for (FileItem item : list) {
if(item.isFormField()){
String name=item.getFieldName();
String value=item.getString("UTF-8");
System.out.println(name+"="+value);
}else{
String filename=item.getName();
System.out.println(filename);
if(filename==null||filename.trim().equals("")){
continue;
}
//处理获取到的上传文件的文件名的路径部分,只保留文件名部分
filename=filename.substring(filename.lastIndexOf("\\")+1);
//获取item文件上传输入流
InputStream in=item.getInputStream();
//创建一个文件输出流
FileOutputStream out=new FileOutputStream(savePath+"\\"+filename);
byte[] buffer=new byte[1024];
int len=0;
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
item.delete();
message="文件上传成功";
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("message", message);
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
jsp页面
<%@ page language="java" pageEncoding="UTF-8"%>
上传用户:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
${message}版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。