【转】jsp+servlet和SSM分别是如何实现文件上传(示例)

原文地址:https://blog.csdn.net/niceliusir/article/details/78453560

以下是jsp+servlet和SSM分别是如何实现文件上传的方法示例

两种模式的upload.jsp文件都一样,(注意要加上enctype=”multipart/form-data”)如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <form action="指定控制器" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>文件:</td>
                <td><input type="file" name="uploadfile"></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="upload" value="上传"></td>
            </tr>
        </table>

    </form>

</body>
</html>

传统的jsp+servlet开发实现上传
UploadServlet.java中的doPost()如下:

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;chartset=utf-8");
    request.setCharacterEncoding("utf-8");
    // 上传的用户名
    String value = null;
    // 上传的文件名
    String fileName = null;
    // 上传的目标路径
    String filePath = request.getSession().getServletContext().getRealPath("/upload");

    // 1.判断表单上传的编码方式
    if(ServletFileUpload.isMultipartContent(request)){
        // 2.创建fileItem工厂
        FileItemFactory factory = new DiskFileItemFactory();
        // 3.创建上传解析对象
        ServletFileUpload sfu = new ServletFileUpload(factory);
        // 4.解析上传的表单
        List<FileItem> fileItemList = null;
        try {
            fileItemList = sfu.parseRequest(request);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for(FileItem f : fileItemList){
            if(f.isFormField()){// 普通表单元素
                String name = f.getFieldName();
                if(name.equals("username")){
                    value = f.getString("utf-8");
                }
            }else{// 文件
                fileName = f.getName();
                File file = new File(filePath + "/" + fileName);
                try {
                    f.write(file);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                response.getWriter().print(value + "上传了" + fileName + "已成功!");
            }

        }
    }

}

SSM框架主要是spring MVC处理器对上传组件进行了封装,使得代码简化了很多
处理器中的处理上传文件的方法如下:

/**
* 文件上传
 *TODO
 *LIU
 * @param request
 * @param response
 * @return
 *上午10:34:15
 */
@RequestMapping("uploadFile.action")
public ModelAndView uploadFile(@RequestParam("uploadfile") CommonsMultipartFile cmf, HttpServletRequest request) throws Exception{

    // 接收普通的用户名的话,用参数request来接收
    String uname = request.getParameter("uname");
    String path = "F:\upload\" + cmf.getOriginalFilename();
    File file = new File(path);

    cmf.transferTo(file);

    mav = new ModelAndView("uploadResult.jsp");
    String mess = cmf.getOriginalFilename() + "上传成功了!";
    mav.addObject("mess", mess);
    mav.addObject("uname", uname);
    return mav;
}
原文地址:https://www.cnblogs.com/dirgo/p/9266733.html