Ruby:在heroku中几小时内突然找不到上传的文件

时间:2015-03-14 06:20:32

标签: java ruby heroku sinatra

我有以下Ruby Sinatra的上传代码来上传图像文件:

post "/upload" do 
  File.open("public/uploads/" + params["image"][:filename], "wb") do |f|
    f.write(params["image"][:tempfile].read)
  end
end

以下Java代码将图像文件上传到example.com/upload:

private static String boundary;
private static final String LINE_FEED = "\r\n";
private static HttpURLConnection httpConn;
private static OutputStream outputStream;
private static PrintWriter writer;

public static void upload(String requestURL, String fieldName, File
uploadFile) throws IOException {

    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);

    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED);
    writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED).flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();
    httpConn.getInputStream();
    httpConn.disconnect();
}

File uploadFile = new File("C:/myimage.png");
upload("http://www.example.com/upload", "image", uploadFile);

我的网站托管在heroku。

调用upload()后,图像文件成功上传,我可以在example.com/upload/myimage.png中访问它

但问题是:几个小时之后,当我检查网址以查看myimage.png时,我收到“Not Found”错误(heroku日志中的404错误)

有什么想法吗?

抱歉我的英文不好:|

1 个答案:

答案 0 :(得分:4)

您不应将文件存储到heroku的本地文件系统中。来自docs

  

短暂的文件系统

     

每个dyno都有自己的短暂文件系统   最近部署的代码的最新副本。在dyno期间   生命周期,其运行进程可以将文件系统用作临时文件   暂存器,但没有写入的文件对进程可见   任何其他的dyno和任何写的文件都会被丢弃   dyno被停止或重新启动。

建议不要在本地存储文件,而是将文件上传到AWS S3或其他云存储系统。