如何在相对目录中上传文件

我已经创建了一个应用程序,我们可以上传任何将保存在本地给定目录中的文件。 我想修改它,我想为部门添加一个下拉(有多个选项,即楼层,商店,部分)。 即如果我们要在’Store’文件夹中上传文件,我们可以选择’Store’选项,文件将上传到’Store’文件夹。 ‘Floor’和’Section’相同。 我只需要任何示例链接。 我在liferay中做到了。

import org.apache.commons.io.FileUtils; import com.liferay.portal.kernel.upload.UploadPortletRequest; import com.liferay.portal.util.PortalUtil; import com.liferay.util.bridges.mvc.MVCPortlet; public class UploadDirectory extends MVCPortlet { private final static int ONE_GB = 1073741824; private final static String baseDir = "/home/xxcompny/workspace"; private final static String fileInputName = "fileupload"; public void upload(ActionRequest request, ActionResponse response) throws Exception { UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request); long sizeInBytes = uploadRequest.getSize(fileInputName); if (uploadRequest.getSize(fileInputName) == 0) { throw new Exception("Received file is 0 bytes!"); } File uploadedFile = uploadRequest.getFile(fileInputName); String sourceFileName = uploadRequest.getFileName(fileInputName); File folder = new File(baseDir); if (folder.getUsableSpace() < ONE_GB) { throw new Exception("Out of disk space!"); } File filePath = new File(folder.getAbsolutePath() + File.separator + sourceFileName); FileUtils.copyFile(uploadedFile, filePath); } } 

JSP就在这里

      <aui:form action="" enctype="multipart/form-data" method="post">  Store Floor Department     

我希望文件将上传到所属文件夹中。

我有一些类似的任务将文件上传到指定的文件夹,因此根据您的要求进行位修改代码:

 public void upload(ActionRequest request, ActionResponse response) throws Exception { UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request); long sizeInBytes = uploadRequest.getSize(fileInputName); if (sizeInBytes == 0) { throw new Exception("Received file is 0 bytes!"); } File uploadedFile = uploadRequest.getFile(fileInputName); String sourceFileName = uploadRequest.getFileName(fileInputName); /* selected folder from UI */ String paramFolder = uploadRequest.getParameter("folder"); byte[] bytes = FileUtil.getBytes(uploadedFile); if (bytes != null && bytes.length > 0) { try { /* Create folder if doesn't exist */ File folder = new File(baseDir + File.separator + paramFolder); if (!folder.exists()) { folder.mkdir(); } /* Write file to specified location */ File newFile = new File(folder.getAbsolutePath() + File.separator + sourceFileName); FileOutputStream fileOutputStream = new FileOutputStream(newFile); fileOutputStream.write(bytes, 0, bytes.length); fileOutputStream.close(); newFile = null; } catch (FileNotFoundException fnf) { newFile = null; /* log exception */ } catch (IOException io) { newFile = null; /* log exception */ } } } 

您可以使用以下代码

 String user_selected_option=request.getParameter("userSel") realPath = getServletContext().getRealPath("/files"); destinationDir = new File(realPath+"/"+user_selected_option); // save to destinationDir