当前位置: 首页 > 工具软件 > JSController > 使用案例 >

文件上传,html、js及Controller,完整代码

杜志
2023-12-01

一、非form表单提交
html页面

<!DOCTYPE html>
<html>
 <head>
	 <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>文件上传</title>
 </head>
 <body>
	 <div>
	      <input type="file" id="file" name="myfile" />
	      <input type="button" onclick="UpladFile()" value="上传" />
	</div>
 </body>

js

<script>
     /*附件上传*/
     function UpladFile() {
         var fileObj = document.getElementById("file").files[0]; // 获取文件对象
         var FileController = "../../upladFile";                    // 接收上传文件的后台地址
         // FormData 对象
         var form = new FormData();
         /*form.append("name", "tom");  */                      // 可以增加表单数据
         form.append("file", fileObj);                           // 文件对象
         // XMLHttpRequest 对象
         var xhr = new XMLHttpRequest();
         xhr.open("post", FileController, true);
         xhr.onload = function () {
             alert("上传完成!");
         };
         xhr.send(form);

     }
 </script>

二、form表单提交
html页面

<!DOCTYPE html>
<html>
 <head>
	 <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>文件上传</title>
     <script type="text/javascript" src="../js/jquery.ui.widget.js?v=0.12"></script>
     <script type="text/javascript" src="..js/jquery.iframe-transport.js?v=0.12"></script>
     <script type="text/javascript" src="../js/jquery.fileupload.js?v=0.12"></script>
     <script src="../js/uploadPreview.js" type="text/javascript?v=0.12"></script>
 </head>
 <body>
	 <form action="../../upladFile" method="post" enctype="multipart/form-data">
           <input style="" type="file" name="files" accept=""/>
           <input type="submit" value="上传" id="fileupload4" />
     </form>
 </body>

js

<script>
     /*附件上传*/
     var isExple = false;
     $('#fileupload4').fileupload({
         dataType: 'json',
         progressall: function (e, data) {
             var progress = parseInt(data.loaded / data.total * 100, 10);
             if (progress > 99) {
                 alert("上传成功");
             }
         },
         done: function (e, data) {
             $('.progress-bar').text("上传成功");
         },
         success: function (result, textStatus, jqXHR) {
             if(isExple){
                 //set录入名称
             }
         },
     });
 </script>

Controller

@RequestMapping(params = "upladFile", method =  RequestMethod.POST)
    @ResponseBody
    public synchronized LinkedList<FileMeta> upladFile( MultipartHttpServletRequest request, HttpServletResponse response, HttpServletRequest request2) 
   	    Iterator<String> itr = request.getFileNames();
        while (itr.hasNext()) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");
            /** 构建文件保存的目录* */
            String logoPathDir = "/business/xfWei/upload/"
                    + dateformat.format(new Date());
            /** 得到文件保存目录的真实路径* */
            String logoRealPathDir = request.getSession().getServletContext()
                    .getRealPath(logoPathDir);
            /** 根据真实路径创建目录* */
            File logoSaveFile = new File(logoRealPathDir);
            if (!logoSaveFile.exists())
                logoSaveFile.mkdirs();
            /** 页面控件的文件流* */
            MultipartFile multipartFile = multipartRequest.getFile("file");
            /** 获取文件的后缀* */
            String suffix = multipartFile.getOriginalFilename().substring(
                                        multipartFile.getOriginalFilename().lastIndexOf("."));
            /** 使用UUID生成文件名称* */
            String logImageName = UUID.randomUUID().toString() + suffix;// 构建文件名称
            /** 拼成完整的文件保存路径加文件* */
            String fileName = logoRealPathDir + File.separator + logImageName;
            System.out.println("upload-》文件保存全路径" + fileName);
            File file = new File(fileName);
            try {
                FileCopyUtils.copy(mpf.getBytes(), new File(fileName));
                System.out.println("上传成功!");
            } catch (IOException e) {
                System.out.println("上传失败!");
                e.printStackTrace();
            }
            System.out.println("2.4 add to files");
            files.add(fileMeta);

            System.out.println("success uploaded=" + files.size());
        }
        return files;
    }
 类似资料: