关于jsp中<input type="file">获取路径问文件名,获取完全路径问题

本文介绍了一种适用于多种浏览器的JavaScript方法,用于获取上传文件的完整路径,包括IE、Firefox等主流浏览器。该方法通过选择文件元素并使用特定的代码片段来实现,确保了跨浏览器的兼容性和稳定性。

原来上传文件用js获取文件路径只需var obj=document.getElementByid(id);var path=obj.value;即可。但是升级浏览器后,获取的路径是文件名字。

网上查了一下,看到一个方法比较不错,适用于各种浏览器,返回图片绝对路径

obj就是上文提到的obj

function getFullPath(obj)
{
if(obj)
{
//ie
if (window.navigator.userAgent.indexOf("MSIE")>=1)
{
obj.select();
return document.selection.createRange().text;
}
//firefox
else if(window.navigator.userAgent.indexOf("Firefox")>=1)
{
if(obj.files)
{
return obj.files.item(0).getAsDataURL();
}
return obj.value;
}
return obj.value;
}
}

<!DOCTYPE html> <html> <head> <title>文件传输系统</title> <style> .container { max-width: 600px; margin: 20px auto; padding: 20px; } .form-group { margin-bottom: 15px; } button { padding: 8px 15px; background: #4CAF50; color: white; border: none; cursor: pointer; } </style> </head> <body> <div class="container"> <!-- 文件上传区域 --> <div class="form-group"> <h2>文件上传</h2> <input type="file" id="fileInput"> <button onclick="uploadFile()">上传文件</button> <div id="uploadStatus"></div> </div> <!-- 文件下载区域 --> <div class="form-group"> <h2>文件下载</h2> <input type="text" id="filenameInput" placeholder="输入文件名"> <button onclick="downloadFile()">下载文件</button> <div id="downloadStatus"></div> </div> </div> <script> // 文件上传函数 async function uploadFile() { const fileInput = document.getElementById('fileInput'); const statusDiv = document.getElementById('uploadStatus'); if (!fileInput.files[0]) { statusDiv.innerHTML = '<span style="color:red">请选择文件</span>'; return; } const formData = new FormData(); formData.append('file', fileInput.files[0]); try { const response = await fetch('/upload', { method: 'POST', body: formData }); const result = await response.json(); if (result.success) { statusDiv.innerHTML = `✓ 上传成功: ${result.filename}`; } else { statusDiv.innerHTML = `✗ 上传失败: ${result.message}`; } } catch (error) { statusDiv.innerHTML = `✗ 网络错误: ${error.message}`; } } // 文件下载函数 function downloadFile() { const filename = document.getElementById('filenameInput').value; if (!filename) { document.getElementById('downloadStatus').innerHTML = '<span style="color:red">请输入文件名</span>'; return; } window.open(`/download?filename=${encodeURIComponent(filename)}`, '_blank'); } </script> </body> </html> 乱码
10-27
创建Web项目,导入相关JAR包; <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency> 创建并配置web.xml文件; <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>Springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:SpringMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> 添加用于上传的jsp页面; <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title>文件上传</title> </head> <body> <table border="1"> <tr> <td width="500" align="center">文件上传</td> </tr> <tr> <td> <form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data"> <input type="file" name="uploadfiles" multiple="multiple"/><br> <input type="submit" value="上传"><br> </form> </td> </tr> <c:forEach items="${msgs}" var="msg"> <tr><td align="center" colspan="2" style="color: red">${msg}</td></tr> </c:forEach> </table> </body> </html> 创建控制类用于上传文件; package com.springmvc.controller; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/file") public class FileUploadController { @RequestMapping("/upload") public String fileUpload(ArrayList<MultipartFile> uploadfiles, HttpServletRequest request) { //定义列表msgs保存提示信息 ArrayList<String> msgs = new ArrayList<>(); if (uploadfiles.get(0).getSize() > 0) { //判断是否上传文件 for (MultipartFile file : uploadfiles) { //循环获取文件 //判断文件不为空且大小大于0 if (!file.isEmpty() & file.getSize() > 0) { //获取文件原始名称 String originalFilename = file.getOriginalFilename(); //获取服务器中的文件夹路径 String path = request.getServletContext().getRealPath("/upload/"); //设置文件保存到服务器的目标路径 String filePath = path + originalFilename; try { //保存文件内容到目标路径 file.transferTo(new File(filePath)); } catch (IOException e) { msgs.add(filePath + "保存失败"); } msgs.add(filePath +"保存成功"); } } } else msgs.add("上传文件失败"); request.setAttribute("msgs", msgs); return "fileUpload"; } } 添加配置文件; <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.springmvc.controller"/> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--配置视图控制器,指定文件上传页面的映射路径--> <mvc:view-controller path="/file/fileupload" view-name="fileUpload"/> <mvc:view-controller path="/file/filedownload" view-name="fileDownload"/> <!--配置注解驱动--> <mvc:annotation-driven/> <!--配置文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--指定请求的编码方式--> <property name="defaultEncoding" value="UTF-8"></property> <!--指定允许上传文件的大小,此处设置最大值为1 M,单位为字节--> <property name="maxUploadSize" value="1024000"></property> </bean> </beans> 添加上传成功的消息页面。 文件下载: 创建控制器类: package com.springmvc.controller; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/file") public class FileDownloadController { @RequestMapping("/download") public ResponseEntity<byte[]> FileDownload(HttpServletRequest request, String fileName) throws IOException { //获取下载文件的路径 String filepath = request.getServletContext().getRealPath("/upload/") + fileName; //创建该文件的对象 File file = new File(filepath); //将文件读取到字节数组中 byte[] bytes = FileUtils.readFileToByteArray(file); //创建HttpHeaders对象设置响应头信息 HttpHeaders headers = new HttpHeaders(); //设置浏览器以“UTF-8”编码方式显示文件名 fileName = URLEncoder.encode(fileName, "UTF-8"); //设置以下载的方式打开文件,并指定文件名称 headers.setContentDispositionFormData("attachment", fileName); //设置文件的下载方式为二进制流 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } } 添加用于上传的jsp页面; <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>文件下载</title> </head> <body> <table border="1"> <tr> <td width="350" align="center">下载列表</td> </tr> <tr> <td> <a href="${pageContext.request.contextPath}/file/download?fileName=微信图片_20250612231528.jpg"> 这是一张图片</a><br> </td> </tr> </table> </body> </html> 实验成果: 修改一下
11-01
package com.foresealife.newglschannel.grp.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import com.foresealife.newglschannel.comm.Constant; import com.foresealife.newglschannel.grp.domain.GrpBonusMangRateDomain; import com.foresealife.newglschannel.grp.domain.GrpOrgInfoSettingDomain; public class GrpOrgInfoSettingController { /** * 进入主页面 * * @param filterMask * @param model * @param request * @param response * @return */ @GetMapping(value = "/newgrp/CombinedRatio/CombinedRatioMain") public String mainPage(GrpOrgInfoSettingDomain filterMask, Model model, HttpServletRequest request, HttpServletResponse response) { model.addAttribute(Constant.FILTER_MASK, filterMask); return "newgrp/salary/CombinedRatio/CombinedRatioMain"; } } <%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title></title> <%@ include file="/WEB-INF/views/commons/head.jsp"%> </head> <script type="text/javascript"> <%--查询--%> function queryAction(){ if (!$('#paginateForm').form('validate')) { return false; } var wd = $("#body").width(); var data = $("#paginateForm").serialize(); var send_url = "${ctx}newgrp/grpFundTaxFee/query.do?"+data; var col_size = 4; $('#GrpCombinedRatioTable').datagrid({ title:'查询信息', width:wd, url:send_url, columns:[[ ]], pagination:true }); } <%--导出--%> function exportData(){ if(!$('#paginateForm').form('validate')){ return false; } queryAction(); var downUrl = "${ctx}commons/download/downReport"; $("#paginateForm").attr("action", downUrl); $("#paginateForm").submit(); } <%--页面加载触发--%> $(function(){ $("#reset").bind("click",function(){ $("#paginateForm input").attr("value",""); $("#paginateForm select").combobox("setValue",""); }); }); </script> <body id="body"> <sfform:form modelAttribute="filterMask" id="paginateForm"> <div class="layout_div"> <div class="navigation_div"> <span class="font_heading1">薪资基础设置>></span><a href="#">综合成本率设置</a> <input name="repName" id="repName" value="" type="hidden" /> <input name="repSubName" id="repSubName" value="01" type="hidden" /> </div> <fieldset class="fieldsetdefault"> <legend>查询</legend> <table class="layouttable" id="input_info"> <tr> <td class="layouttable_td_label">年度:</td> <td class="layouttable_td_widget"><sfform:input path="ym" id="ym" class="input_text Wdate required" readonly="true" onclick="WdatePicker({skin:'whyGreen',dateFmt:'yyyy'})" /> <strong style="color: red">*</strong></td> <td class="layouttable_td_label">机构:</td> <td class="layouttable_td_widget"><%@ include file="/WEB-INF/views/commons/organ.jsp"%> </td> </tr> </table> <table class="query_table"> <tr> <td class="td_right"> <a class="easyui-linkbutton" onclick="javascript:queryAction()" iconCls="icon-search" id="search">查询</a> <a class="easyui-linkbutton" onclick="javascript:batchAdd()" iconCls="icon-add" id="add">导入</a> <a class="easyui-linkbutton" onclick="javascript:exportData()" iconCls="icon-xls" id="search">数据导出</a> <a class="easyui-linkbutton" onclick="javascript:void(0);" iconCls="icon-cancel" id="reset">重置</a> </td> </tr> </table> </fieldset> <div class="layout_div_top_spance"> <table id="GrpCombinedRatioTable"></table> </div> </div> </sfform:form> <form id="editForm" method="post"></form> </body> </html>为什么通过newgrp/CombinedRatio/CombinedRatioMain却无法进入CombinedRatioMain
最新发布
11-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值