gpt4 book ai didi

java - 如何获取我要使用多部分上传的文件的名称

转载 作者:行者123 更新时间:2023-12-02 02:51:14 29 4
gpt4 key购买 nike

我想获取我正在上传的文件的名称。目的是获取文件的完整路径(包括带扩展名的文件名)。jsp:-

<form action="go" method="post" enctype="multipart/form-data">  
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>

</form>

servlet:-

        protected void processRequest(HttpServletRequest request,  HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String filename=request.getParameter("fname"); //unable to get fname
MultipartRequest m=new MultipartRequest(request,"d:/new");
String filePath="d:/new".concat(filename);
out.print("successfully uploaded");
out.print(filePath);
}

最佳答案

A.Plain Servlet 解决方案:

<强>1。获取javax.servlet.http.Part来自 HttpServletRequest

   String fileName = null;
//Get all the parts from request and write it to the file on server
for (Part part : request.getParts()) {
fileName = getFileName(part);
}

<强>2。从零件中获取文件名

   /**
* Utility method to get file name from HTTP header content-disposition
*/
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
System.out.println("content-disposition header= "+contentDisp);
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length()-1);
}
}
return "";
}

================================================== ====

基于B.Spring的解决方案:

使用spring,当你上传文件时,requestorg.springframework.web.multipart.MultipartHttpServletRequest的实例

您可以从 MultipartHttpServletRequest 获取上传的文件名,如下所示。

   // cast request
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// get filenames as iterator

Iterator<String> iterator = multipartRequest.getFileNames();

while (iterator.hasNext()) {
String uploadedFileName = (String) iterator.next();

}

关于java - 如何获取我要使用多部分上传的文件的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43813392/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com