AJAX提交multipartform-data类型文件到后台以及后台如何获取

    科技2025-01-22  56

    一.前端代码 1.htlm代码

    <form id="viaBox" method="post" enctype="multipart/form-data"> <input type="hidden" name="code" class="via_idCode" /> <img class="user_via" src="<%=basePath%>web/img/default.png" /> <input type="file" accept="image/*" name="via_photo" class="via_photo" id="via_photo" onchange="changeVia()" /> </form>

    2.js代码

    function changeVia(){ var reads = new FileReader(); var img = document.querySelector(".via_photo").files[0]; if(img.size <= 1024*1024*1){ reads.readAsDataURL(img); reads.onload = function(e){ document.querySelector(".user_via").src=this.result;//将图片url转成base64 } $.ajax({ type:"post", url:url, cache:false,//上传数据不需要缓存 contentType:false,//已经在表单的entype处声明了multipart/form-data processData:false,//data值是FormData对象,不需要对数据做处理 data:new FormData($("#viaBox")[0]), success:function(res){ console.log(res); }, error:function(err){ console.log(error); } }) }else{ console.log("上传图片不能超出1M"); } }

    二.后端代码 这里我分别引入了commons-fileupload-1.4.jar和commons-io-2.7.jar 可以去apache官网下载(http://apache.org/)

    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { request.getRequestDispatcher("WEB-INF/test01.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); // 判断form的enctype是否为multipart请求 if (!ServletFileUpload.isMultipartContent(request)) { throw new RuntimeException("当前请求不支持!"); } try { String fileValue = null ; // 创建FileItem工产 DiskFileItemFactory factory = new DiskFileItemFactory(); //设置使用临时文件的边界值,大于该值(1M)上传文件将保存在临时文件中,反之,写入内存中 factory.setSizeThreshold(1024*1024*1);//设置边界值为1M //设置临时文件 String tempPath = this.getServletContext().getRealPath("/temp"); File temp = new File(tempPath); factory.setRepository(temp); // 创建文件上传核心組件 ServletFileUpload upload = new ServletFileUpload(factory); // 解决上传的文件名乱码 upload.setHeaderEncoding("UTF-8"); // 解析请求 List<FileItem> items = upload.parseRequest(request); //遍历items for(FileItem item :items){ if(item.isFormField()){//是普通表单项目 String fieldName = item.getFieldName();//获得name值 fileValue = item.getString();//获得value值 System.out.println(fieldName+":"+fileValue); }else{//不是普通表单项目 //上传文件的原始名称 String fileName = item.getName(); //解决上传文件重名 fileName = System.currentTimeMillis()+ fileName; //获取输入流 InputStream is = item.getInputStream(); //获取文件保存在服务器的imgs文件夹中 String path = this.getServletContext().getRealPath("/imgs"); response.getWriter().write(path+"\\"+fileValue+"\\"+fileName); path = path+"/"+fileValue; File dirFile = new File(path); if(!dirFile.exists()){ dirFile.mkdir(); } //创建目标文件,用来存放用户上传的文件 File descFile = new File(path ,fileName); //创建文件输出流 OutputStream os = new FileOutputStream(descFile); //将输入流的数据写入到输出流中 int len = -1; byte[] buffer = new byte[1024]; while((len = is.read(buffer)) != -1){ os.write(buffer,0,len); } //关闭流 os.close(); is.close(); item.delete();//删除临时文件 } } } catch (FileUploadException e) { e.printStackTrace(); } }
    Processed: 0.012, SQL: 8