-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUploadModule.pm
More file actions
85 lines (61 loc) · 2.25 KB
/
Copy pathUploadModule.pm
File metadata and controls
85 lines (61 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package UploadModule;
use nginx;
use HTTP::Body;
use IO::File;
use File::Copy;
sub handler {
my $r = shift;
if ($r->request_method ne "POST") {
return HTTP_BAD_REQUEST;
}
return HTTP_BAD_REQUEST unless $r->has_request_body(\&post);
}
sub post {
my $r = shift;
my $upload_dir = $r->variable("upload_dir");
unless ($upload_dir) {
return error($r, HTTP_INTERNAL_SERVER_ERROR, "Upload directory not set");
}
my $tmp_nginx_body_file = $r->request_body_file;
my $fh = IO::File->new($tmp_nginx_body_file, 'r') or return error($r, HTTP_INTERNAL_SERVER_ERROR, "Unable to open request body file");
# Initialize HTTP::Body
my $content_type = $r->header_in('Content-Type');
my $content_length = $r->header_in('Content-Length');
my $body = HTTP::Body->new($content_type, $content_length);
# enable automatic deletion of temporary files at DESTROY-time.
$body->cleanup(1);
# Read the file contents
my $buffer;
while (my $bytes_read = $fh->read($buffer, 1024)) {
$body->add(substr($buffer, 0, $bytes_read));
}
unless (defined $body->{upload} && defined $body->{upload}->{file} && ref $body->{upload}->{file} eq 'HASH') {
return error($r, HTTP_INTERNAL_SERVER_ERROR, "Cannot parse multipart data");
}
# Get the parsed params
my $tempname = $body->{upload}->{file}->{tempname};
my $filename = $body->{upload}->{file}->{filename};
# Check for "filename.extension" format
unless ($filename =~ /^[a-zA-Z0-9]+\.[a-zA-Z0-9]{1,100}$/) {
return error($r, HTTP_BAD_REQUEST, "Invalid filename format");
}
my $destination = $upload_dir . "/" . $filename;
unless (move($tempname, $destination)) {
return error($r, HTTP_INTERNAL_SERVER_ERROR, "Unable to move uploaded file");
}
$r->status(HTTP_CREATED);
my $response = '{"message": "File uploaded successfully"}';
$r->send_http_header('application/json');
$r->print($response);
return OK;
}
sub error {
my ($r, $status, $message) = @_;
$r->log_error($status, $message);
$r->header_out('Content-Type', 'text/plain');
$r->status($status);
$r->send_http_header();
$r->print("Upload has failed, see the logs");
return OK;
}
1;