其他分享
首页 > 其他分享> > 2021-09-24

2021-09-24

作者:互联网

上传文件到服务器

package servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

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 javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
@WebServlet(urlPatterns = "/uploadtest")
public class UploadServlet 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 {
        //创建上传文件对象
        SmartUpload smartUpload = new SmartUpload();

        //初始化上传操作
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024, true);
        smartUpload.initialize(pageContext);
        //设置编码
        smartUpload.setCharset("utf-8");
        //上传
        try {
            smartUpload.upload();

            //获取文件信息
            File file = smartUpload.getFiles().getFile(0);
            String fileName = file.getFileName();
            String contentType = file.getContentType();
            //指定上传的路径
            String uploadpath = "/uploadfiles/"+fileName;
            //保存到指定位置
            file.saveAs(uploadpath,File.SAVEAS_VIRTUAL);//虚拟路径
            //存一下文件名称
            req.setAttribute("filename",fileName);
            //跳转到成功页面
            req.getRequestDispatcher("succes.jsp").forward(req,resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }


    }
}

标签:24,09,resp,req,smartUpload,2021,import,servlet,javax
来源: https://blog.csdn.net/weixin_45653293/article/details/120461192