javaweb上传文件前后台代码示例

技术要点:
前端使用jquery插件jquery.upload2.js上传文件;
后端使用springMVC框架

前提:需在applicationContext.xml文件中添加支持文件上传的配置


    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />


//前端代码,使用了jquery上传文件插件:jquery.upload2.js
<body>
<input type="file" name="f_sjjtpc" />
body>
<script>
    function ajaxSubmitTpc() {
        $("input[name=f_sjjtpc]").upload({
            url: './api/service/fileupload/uploadsjjtpc',
            // 其他表单数据
            params: { name: 'pxblog' },
            // 上传完成后, 返回json, text
            dataType: 'json',
            onSend: function (obj, str) {  return true; },
            // 上传之后回调
            onComplate: function (data) {
                alert(data.file);
            }
        });
        $("input[name=f_sjjtpc]").upload("ajaxSubmit")
    }
script>


后台代码:

//后台使用springmvc框架
/**
     *后台接收前端发送过来的文件 
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadsjjtpc", produces = "application/json")
    public Object uploadSjjTpc(HttpServletRequest request) throws IOException {
        Map resultMap = new HashMap();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        // 1. build an iterator
        Iterator itr = multipartHttpServletRequest.getFileNames();
        MultipartFile mpf = null;
        // 2. get each file
        while (itr.hasNext()) {
            // 2.1 get next MultipartFile
            mpf = multipartHttpServletRequest.getFile(itr.next());
            // System.out.println(mpf.getOriginalFilename() + " uploaded! ");
            log.info(mpf.getOriginalFilename() + " uploaded! " + "---" + mpf.getSize() / 1024 + " Kb");
            log.info(mpf.getContentType());
            InputStream inputStream = mpf.getInputStream();
            String contextPath = request.getContextPath();
            String CurrentClassFilePath = this.getClass().getResource("").getPath();
            String realPath = request.getSession().getServletContext().getRealPath("");
            log.debug("realpath---" + realPath);
            log.debug("contextPath---" + contextPath);
            log.debug("CurrentClassFilePath---" + CurrentClassFilePath);
            InputStream excelInputStream = mpf.getInputStream();
            try {
                // 拷贝文件到指定的目录
                FileUtils.copyInputStreamToFile(inputStream,
                        new File(realPath + "/files/" + mpf.getOriginalFilename()));
                // 判断上传的文件的格式是否符合要求
            } catch (Exception e) {
                e.printStackTrace();
                log.debug("拷贝文件失败" + e.getMessage());
            }
        }
        return resultMap;

    }

你可能感兴趣的:(java,WEB,springmvc)