How to upload file in relative directory

巧了我就是萌 提交于 2019-12-07 09:14:25

I had somewhat similar task to upload files to specified folders, so following is bit modified code as per your requirement:

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 */
        }
    }
}
Gourav malhotra

You can use the below code

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

// save to destinationDir 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!