标签:对象 file over request请求 ext head 返回 system commons
实现文件的上传功能现在有两种方式:
首先使用第一种:
1.创建项目,引入commons-fileupload jar 和javax.servlet-api
2.创建jsp页面:
3.程序处理:
@WebServlet("/upload")
public class Upload extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//磁盘文件项工厂
DiskFileItemFactory factory=new DiskFileItemFactory();
//核心解析对象
ServletFileUpload servletFileUpload=new ServletFileUpload(factory);
//解析request请求,返回list
try {
List<FileItem> fileItems=servletFileUpload.parseRequest(req);
//遍历集合
for (FileItem fileItem : fileItems){
if (fileItem.isFormField()){
String name=fileItem.getFieldName();
String value=fileItem.getString("UTF-8");
System.out.println(name+"-"+value);
}
else{
String picName=fileItem.getName();
if (picName!=null&&picName.length()!=0){
String url=null;
String fileName=UploadUtils.getUUID(picName);
//获取输入流,图片的内容流?
InputStream is=fileItem.getInputStream();
//存放图片的路径
String path=this.getServletContext().getRealPath("/images");
System.out.println(path);
//图片的地址
url=path+"\\"+fileName;
//写入到路径中
OutputStream os=new FileOutputStream(url);
int len=0;
byte[] b=new byte[1024];
while((len=is.read(b))!=-1){
os.write(b,0,len);
}
is.close();
os.close();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
4.异常处理:
程序报错:系统找不到路径
解决办法:在这个路径下新增images文件夹后。图片上传成功。
仅使用javax-servlet -api 包
1.第一,第二步骤同上
2.代码处理:
@WebServlet(value = "/upload")
@MultipartConfig
public class PartDemo extends HttpServlet {
private HttpServletRequest request;
private HttpServletResponse response;
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.request=req;
this.response=resp;
getFileUpload();
}
public void getFileUpload(){
String username=request.getParameter("username");
String password=request.getParameter("password");
System.out.println(username+"-"+password);
try {
//接收图片
Part part=request.getPart("photo");
//生成文件名
String fileName=UUID.randomUUID().toString()+ LocalDate.now();
//项目路径
String path=request.getServletContext().getRealPath("/images");
//图片的格式
String contentDisposition=part.getHeader("content-disposition");
System.out.println(contentDisposition);
String suffix=contentDisposition.substring(contentDisposition.lastIndexOf("."),contentDisposition.length()-1);
//图片的路径
String url=path+"\\"+fileName+suffix;
part.write(url);
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
}
3.异常处理:
4.结果
成功!
标签:对象 file over request请求 ext head 返回 system commons
原文地址:https://www.cnblogs.com/liu-chen/p/11813836.html