将String写入文件,用户从<input type =“file”/>中选择

时间:2015-08-13 07:16:22

标签: java jsp servlets

我想将一个String写入用户选择的文件中。我无法这样做,因为我需要fileName和fileLocation将我的String写入文件。但是request.getParamater(“”)只给了我fileName。我知道由于安全问题它不会返回fileLocation。然后,如何从我在jsp上选择的文件中编写我的String。请指教。

2 个答案:

答案 0 :(得分:3)

您无法直接写入该文件。

简短回答:在服务器上制作一份复制文件。

长答案

1)获取文件。

2)将其保存在服务器上。

3)附加到该文件。不要覆盖。

4)再次使用response将文件发回给用户。

答案 1 :(得分:-2)

执行一些步骤

  • 使用getFileName()方法获取文件名。将其存储在服务器端
  • 如果有人想要再次保存相同的文件名,则在文件名后添加一些日期。这样您就可以轻松获取所有文件而无需更改任何代码。
  • String写入文件后关闭文件并flush
  • 请参阅我已将文件从前端上传并存储在某些本地系统上。当您尝试再次上载Same文件时,它会附加带文件名的日期

    public class uploadFile {
    
    private File myFile;
    private String myFileContentType;
    private String myFileFileName;
    private String destPath;
    
     public String upload() throws IOException {
    try {
    
        destPath = System.getProperty("user.home") +    System.getProperty("file.separator") + "File-Uploads";
        File destFile = new File(destPath, myFileFileName);
        File file1 = new File(destFile.toString());
        boolean b = false;
        Date date = new Date();
        if (!(file1.exists())) {
            b = file1.createNewFile();
    
        }
        if (b) {
            FileUtils.copyFile(myFile, destFile);
        } else {
            String fileContent = "";
            File f = new File(file1.toString());
            FileInputStream inp = new FileInputStream(f);
            byte[] bf = new byte[(int) f.length()];
            inp.read(bf);
            fileContent = new String(bf, "UTF-8");
            System.out.println("file===>" + fileContent);
            String filename = destFile.toString() + date;
            FileWriter fw = new FileWriter(filename, true);
            fw.write(fileContent);
            fw.close();
            FileUtils.copyFile(myFile, destFile);
           }
    
        return SUCCESS;
    } catch (IOException e) {
        return SUCCESS;
    }
    }
    
       public File getMyFile() {
         return myFile;
       }
    
     public void setMyFile(File myFile) {
     this.myFile = myFile;
      }
    
      public String getMyFileContentType() {
      return myFileContentType;
     }
    
    public void setMyFileContentType(String myFileContentType) {
    this.myFileContentType = myFileContentType;
     }
    
     public String getMyFileFileName() {
     return myFileFileName;
     }
    
     public void setMyFileFileName(String myFileFileName) {
     this.myFileFileName = myFileFileName;
      }
      }
    
相关问题