AWS s3在部署并在本地工作后未使用MultipartFile并且无法正常工作将文件上传到tomcat服务器

问题描述 投票:0回答:1

在将文件上传到AWS s3存储桶时,其在本地正常工作。但是,当我在tomcat服务器上部署项目时,它给了错误以编写fileoutputstream ((权限被拒绝)

这里是图像

enter image description here

这是我的代码

private File convertMultiPartToFile(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }

    private String generateFileName(MultipartFile multiPart) {
        return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_");
    }

    private void uploadFileTos3bucket(String fileName, File file) {
        s3client.putObject(
                new PutObjectRequest(bucketName, fileName, file).withCannedAcl(CannedAccessControlList.PublicRead));
    }

并且当我将File更改为Multipartfile时,显示此错误是我的错误

enter image description here

“如果我将文件转换成多个部分,而不是给出(I / O)例外
java file amazon-s3 multipart
1个回答
0
投票
问题在此方法中:

关于S3,没有问题,因为使用

fileOutputstream而出现此问题,没有指定任何文件夹来写入文件。但是默认情况下,它会将文件写入项目中的target文件夹中。

private File convertMultiPartToFile(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; }
所以我通过在上传时为

tomcat

server创建了一个folder来解决了代码。下一次请求到达时。我删除现有目录,然后再次创建它,仅用于写入文件。使用下面的代码:

private File convertMultiPartToFile(MultipartFile file) throws IOException { deleteDir(new File(NsdlUrlListService.einvoicePath)); //delete a dir File files = new File("home/ubuntu/txtgenie/einvoice/"); //create a dir if (!files.exists()) { if (files.mkdirs()) { logger.debug("Multiple directories are created!"); } else { logger.debug("Failed to create multiple directories!"); } } File convFile = new File(file.getOriginalFilename()); FileOutputStream fos = new FileOutputStream("/home/ubuntu/txtgenie/einvoice/"+convFile); logger.info(" File Name:: {} ", file); String fileName = null; byte[] bytes = file.getBytes(); fileName = file.getOriginalFilename(); if (!fileName.equals("No file")) { try { BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(new File("home/ubuntu/txtgenie/einvoice/" + fileName))); bos.write(bytes); bos.close(); } catch (FileNotFoundException fnfe) { logger.debug("File not found" + fnfe); } catch (IOException ioe) { logger.debug("Error while writing to file" + ioe); } } fos.write(file.getBytes()); fos.close(); return convFile; }

删除目录

private boolean deleteDir(File file) { logger.debug("DIR to delete :: " +file); if (file.isDirectory()) { String[] children = file.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir (new File(file, children[i])); if (!success) { return false; } } } logger.debug("The directory : "+file+" : is deleted."); return file.delete(); }

© www.soinside.com 2019 - 2024. All rights reserved.