jsp+servlet实现文件上传与下载功能(jspservlet增删改查 miniui)全程干货

随心笔谈2年前发布 编辑
182 0
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买


import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadAnnexServlet extends HttpServlet {

private static String path=””;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

path=this.getServletContext().getRealPath(“/upload”);

try {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload up=new ServletFileUpload(factory);
List<FileItem> ls=up.parseRequest(request);

for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName=fileItem.getFieldName();
//getName()返回的是文件名字 普通域没有文件 返回NULL
// String Name=fileItem.getName();
String Content=fileItem.getString(“gbk”);
request.setAttribute(FieldName, Content);
} else {

String nm=fileItem.getName().substring(
fileItem.getName().lastIndexOf(“\”) + 1);
File mkr=new File(path, nm);
if (mkr.createNewFile()) {
fileItem.write(mkr);//非常方便的方法
}
request.setAttribute(“result”, “上传文件成功!”);
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute(“result”, “上传失败,请查找原因,重新再试!”);
}
request.getRequestDispatcher(“/pages/admin/annex-manager.jsp”).forward(
request, response);
}

}

© 版权声明

相关文章