0
我正在開發一個簡單的文件上傳器。簡單的文件上傳增加了應該上傳各種文件(影像/ ,視頻/,音頻/ ,文本/和應用程序/ ***)圖像,視頻,音頻,文本分別與應用目錄。我在將路徑(例如video /)附加到@MultipathConfig(location =「/ files/uploads」)註釋中指定的當前目錄時遇到問題。我希望上傳視頻的路徑爲/files/uploads/video/aws_signs_javas_creator.mp4 我正在開發Netbeans 8.02,Ubuntu上的GlassFish Server 4.0。將附加路徑信息追加到@MultipartConfig(位置=「/」)
的index.jsp
<form method="POST" action="upload" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file" multiple/>
</div>
<div>
<button type="submit" name="upload">Upload</button>
</div>
</form>
FileUploader.java
@WebServlet(name = "FileUploader", urlPatterns = {"/upload"})
@MultipartConfig(location = "/files/upload")
public class FileUploadController extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList());
InputStream fileContent = null;
String fileName = null;
String fileType = null;
for (Part filePart : fileParts) {
if (filePart.getSize() != 0) {
fileName = Decorator.getFileName(filePart);
fileType = filePart.getContentType();
fileContent = filePart.getInputStream();
filePart.write(location + fileName);
if(fileType.contains("image/")) {
filePart.write("/images/" + fileName);
} else if(fileType.contains("application/")) {
filePart.write("/applications/" + fileName);
} else if(fileType.contains("video/")) {
filePart.write("/videos/" + fileName);
} else if(fileType.contains("text/")) {
filePart.write("/texts/" + fileName);
} else if(fileType.contains("audio/")) {
filePart.write("/audios/" + fileName);
}
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")){
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
}
下面是捕獲到的異常:java.io.FileNotFoundException:/home/nkengbeza/glassfish-4.1.1/glassfish/domains/domain1/generated/jsp/FilesUploader/files/uploads/images/jquery-logo.png(No這樣的文件或目錄)。我想我的上傳路徑是:/home/nkengbeza/glassfish-4.1.1/glassfish/domains/domain1/iles/uploads/images/jquery-logo.png – byteHunt3r
@ byteHunt3r在我看來,Glassfish忽略了您指定的位置'@ MultipathConfig'註釋和/或錯誤地描述了關於寫位置的Servlet規範。作爲一種解決方法,您可以使用該部分的InputStream並將其自己寫入一個位置,而不是依賴於麻煩的'Part.write(String)'。 – wero