![](/img/trans.png)
[英]using servlet 3.0 I cannot get the actual FileName of an uploaded file
[英]How to get Uploaded filename in java servlet?
我有這個:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
sentfilename = printNames(request);
MultipartRequest multipartRequest = new MultipartRequest(request, ImageDirecoty, 1024*1024*5);
} catch(IOException e){
response.sendError(HttpServletResponse.SC_CONFLICT, "File limit has exceeded or it wasn't an actual image");
System.out.println(e.getMessage());
return;
}
}
public String printNames(HttpServletRequest request) throws IOException, ServletException{
for(Part part : request.getParts()){
Collection<String> headers = part.getHeaders("content-disposition");
if (headers == null)
continue;
for(String header : headers){
String filename = header.substring(header.indexOf("filename=") + 10 , header.length());
String result = filename.replace("\"", "");
return result;
}
}
return null;
}
基本上我是從客戶端上傳一個簡單的文件,現在我需要從請求數據中獲取文件名,可以成功通過printNames
函數獲取文件名,並將請求數據寫入我的文件filepath
,現在的問題是,如我所見doPost() try
如果我先放置printNames
函數,則可以獲取文件名,但它不寫入數據;如果我首先放置MultipartRequest
,則可以獲取文件上傳,但不獲取文件名。
希望不要造成任何困惑,並在此先感謝
您可以從零件對象本身獲取它
String fileName = part.getSubmittedFileName();
例:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Deque<FileInfo> files = new LinkedList<>();
for (Part part : req.getParts()) {
long fileSize = part.getSize();
String fileName = part.getSubmittedFileName();
if (fileSize == 0 && (fileName == null || fileName.isEmpty())) {
continue; // Ignore part, if not a file.
}
FileInfo info = new FileInfo(UUID.randomUUID(), fileSize, fileName, part.getContentType());
files.add(info);
Files.copy(part.getInputStream(), new File(uploads, info.getId().toString()).toPath());
}
req.getSession().setAttribute("uploadedFiles", files);
resp.sendRedirect(applicationUrl + "/upload");
}
來源: http : //ursaj.com/upload-files-in-java-with-servlet-api
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.