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

随心笔谈12个月前发布 admin
106 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);
}

}

© 版权声明

相关文章