springmvc 文件上传

今天药忘吃喽~ 2022-05-16 03:55 497阅读 0赞

jsp页面:











选取文件..       

ajax请求:

  1. <script type="text/javascript"> $(document).ready(function () { //选择文件事件 $("#myfile").change(function(){ $("#uploadFile").val($(this).val()); }); //上送文件 $("#executeUploadFile").click(function(){ if ($("#password").val() == "") { new LightTip().error("请输入上送口令!"); return; } var files = document.getElementById("myfile").files; if (files.length > 0) { new Dialog().confirm('\<h6>您确定要执行上送吗?</h6>\<p>上送后,将无法撤回。</p>' , { buttons: [{ events: function(event) { event.data.dialog.remove(); var files = document.getElementById("myfile").files; var formData = new FormData(); formData.append('files', files[0]); formData.append("password", $("#password").val()); $.ajax({ type: "post", url: "/file/filesUpload.jhtml", processData: false, contentType: false, data: formData, success: function(data){ if (data.code > 0) { new LightTip().success("上送成功!"); document.getElementById("myfile").value = null; $("#uploadFile").val(""); } else { new LightTip().error(data.msg); } }, error : function (data) { new LightTip().error(data.msg); } }); } }, {}] }); } else { new LightTip().error("请选择待上送的文件!"); } }); }); </script>
  2. ----------
  3. controller代码:
  4. @Controller
  5. @RequestMapping("/file")
  6. public class UpLoadController {
  7. @RequestMapping("/filesUpload")
  8. @ResponseBody
  9. public JSONObject filesUpload(@RequestParam MultipartFile[] files, HttpServletRequest request, String password) {
  10. JSONObject jsonObject = new JSONObject();
  11. //多文件上传时需要用数组
  12. for (MultipartFile file : files) {
  13. if (file.getSize() != 0 && password.equals("123456")) {
  14. //得到上传文件的文件名
  15. String filename = file.getOriginalFilename();
  16. //得到文件真实路径
  17. String realPath = request.getSession().getServletContext().getRealPath("") + File.separator;
  18. //生成唯一标识,时间+文件名
  19. String newName = realPath + filename;
  20. File locaFile = new File(newName);
  21. try {
  22. file.transferTo(locaFile);
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. jsonObject.put("code", 1);
  27. } else {
  28. jsonObject.put("code", 0);
  29. }
  30. jsonObject.put("msg", "OK");
  31. }
  32. return jsonObject;
  33. }
  34. }
  35. springmvc配置文件:
  36. <!-- 文件上传配置 -->
  37. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  38. <!-- 上传的最大限制 -->
  39. <property name="maxUploadSize" value="209715200" />
  40. <!-- 默认编码 -->
  41. <property name="defaultEncoding" value="UTF-8" />
  42. <!-- 上传文件的解析 -->
  43. <property name="resolveLazily" value="true" />
  44. </bean>
  45. 新手上路,望多多指教……

发表评论

表情:
评论列表 (有 0 条评论,497人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringMVC文件

    文件上传自然是一个网站必不可少的元素之一,SpringMVC这个网站编程框架自然也有这个东西,下一面举一个例子说明这个问题。 如下图所示,一个简单的上传控件,只让上传bmp、

    相关 SpringMVC_文件

    一、文件上传 1、说明 SpringMVC为文件上传提供了直接的支持,这种支持是通过即插即用的 MultipartResolver 实现的。Spring用 Jak