Nginx上传模块无法创建输出文件

时间:2014-11-25 20:49:42

标签: ruby-on-rails nginx

我正在尝试将Nginx上传模块与Rails后端服务器集成。这是我的服务器配置:

upstream dev_app {
  server 127.0.0.1:3000;
}

server {
  listen [::]:8081 ipv6only=on;

  server_name _;

  root     /Users/me/workspace/dev_app/public;
  index    index.html;

  try_files $uri $uri/index.html $uri.html @dev_app;

  client_max_body_size 512M;
  client_body_buffer_size 2048K;

  location /v2/photos/avatar {
    upload_pass /v2/_photos/avatar;
    upload_store /tmp/uploads 1;
    upload_state_store /tmp/upload_state;
    upload_resumable on;
    upload_store_access user:rw group:rw all:r;
    upload_max_file_size 512M;

    # form fields to be passed to Rails
    upload_set_form_field $upload_field_name.filename "$upload_file_name";
    upload_set_form_field $upload_field_name.path "$upload_tmp_path";
    upload_set_form_field $upload_field_name.content_type "$upload_content_type";
    upload_pass_form_field "^photo$";
    upload_cleanup 400 404 499 500-505;
  }

  location @dev_app {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  Host $http_host;
    proxy_redirect  off;

    proxy_pass http://dev_app;
  }
}

但是,当我尝试上传文件时,总会出现错误。

curl -v --form photo=@photo.jpg http://localhost:8081/v2/photos/avatar
* Hostname was NOT found in DNS cache
*   Trying ::1...
* Connected to localhost (::1) port 8081 (#0)
> POST /v2/photos/avatar HTTP/1.1
> User-Agent: curl/7.37.1
> Host: localhost:8081
> Accept: */*
> Content-Length: 6399
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------0bef04705a84fc2f
>
< HTTP/1.1 100 Continue
< HTTP/1.1 503 Service Temporarily Unavailable
* Server nginx is not blacklisted
< Server: nginx
< Date: Tue, 25 Nov 2014 20:44:05 GMT
< Content-Type: text/html
< Content-Length: 206
< Connection: keep-alive
* HTTP error before end of send, stop sending
<
<html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body bgcolor="white">
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>nginx</center>
</body>
</html>
* Closing connection 0

Nginx错误日志:

2014/11/26 03:44:05 [error] 75010#0: *88 failed to create output file "/tmp/uploads/0/0000000007" for "photo.jpg" (2: No such file or directory), client: ::1, server: _, request: "POST /v2/photos/avatar HTTP/1.1", host: "localhost:8081"

我的Nginx版本是1.6.2。

我做错了吗?

1 个答案:

答案 0 :(得分:0)

最后,我想通了,因为Nginx上传模块没有自动创建文件夹,我们必须手动创建临时文件夹。使用指令upload_store /tmp/uploads 1;,它将生成类似/tmp/uploads/0/00000009/tmp/uploads/1/000000001等的路径。

我们可以通过脚本轻松实现这一目标。有点像这样:

ruby -e 'require "fileutils"; (0..9).each{|i| FileUtils.mkdir_p("/tmp/uploads/#{i}") rescue nil }'