how to read a User uploaded file, without saving it to the database
You are very close. Check the class type of params[:uploaded_file]
, it should typically be either a StringIO
or a Tempfile
object -- both of which already act as files, and can be read using their respective read
method(s).
Just to be sure (the class type of params[:uploaded_file]
may vary depending on whether you are using Mongrel, Passenger, Webrick etc.) you can do a slightly more exhaustive attempt:
# Note: use form validation to ensure that
# params[:uploaded_file] is not null
file_data = params[:uploaded_file]
if file_data.respond_to?(:read)
xml_contents = file_data.read
elsif file_data.respond_to?(:path)
xml_contents = File.read(file_data.path)
else
logger.error "Bad file_data: #{file_data.class.name}: #{file_data.inspect}"
end
If, in your case, it turns out that params[:uploaded_file]
is a hash, make sure that you have not mistakingly flipped the object_name
and method
parameters when invoking file_field
in your view, or that your server is not giving you a hash with keys like :content_type
etc. (in which case please comment on this post with the Bad file_data ...
output from development.log
/production.log
.)
is it possible to read a file without saving it in Rails?
You need to authenticate to the API in order to submit files to Stripe, and it can only happen server-side, since you don't want to store your credentials in your frontend code.
In order to submit a file without saving it, a solution would be to have a controller action taking the submitted file, upload it to the Stripe server and redirecting to whatever route you need:
# Init Stripe client
Stripe.api_key = STRIPE_SECRET_KEY
# Controller
def stripe_file_upload
file = params[:file]
Stripe::File.create({
file: file.tempfile,
purpose: 'dispute_evidence'
})
redirect_to my_custom_path
end
# View
<h1>My Form</h1>
<%= form_tag stripe_file_upload_path, multipart: true do %>
<%= file_field_tag :file, class: "file-input" %>
<%= submit_tag %>
<% end %>
Accessing an uploaded file without actually storing it in the database or on the server -- Ruby on Rails
When the file is uploaded Rails will automatically read it in and make it an instance of Tempfile so it's already stored, it won't however be stored forever on the system.
You can access the file using the normal params[:field_name]
syntax as if the file were any other field (don't forget to set content-type
of the form to multipart/form-data
- i.e.
form_for @mything, :html => {:multipart => true})
and you will get back the tempfile. The tempfile can be read from like any other file.
Rails (Or Maybe Rack I'm not 100% up to date) determines whether to do this or not to uploaded content based on the attachment part of the mulitpart/form-data element containing the file.
It might be possible to override things if you need to though to stop this storage from happening. Common practice however is to just work with the file and then let Ruby deal with the temp file.
Consume content of the file without saving the file with express.js?
This is what can be done when you don't want to store the csv in a file system and read the content. In my case, I had to pass the content of csv file as a string to another server (without saving in local system of server).
const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() })
app.post(
'/users/bulkUpload',
upload.single('csvFile'),
this.usersRoutes.uploadUserData
);
and in uploadUserData()
:
uploadUserData = async(
req: Request,
res: Response,
next: any
): Promise<any> => {
try {
const options = {
formData : {
'upload': String(req.file.buffer)
},
headers: {
authorization: req.token,
'Content-type': 'multipart/form-data'
},
json: true
};
const response = await this.http.post.exec(
'/somePostUrl/',
options
);
return res.status(200).json(response.body);
}catch (error) {
return next(error);
}
}
Here, console.log(String(req.file.buffer))
would show you the content of csv file as a string.
I hope it helps you.
How to manipulate user uploaded files in django without saving it?
I'll assume you're using Django 1.9
(if not, please update your question to reflect your version of Django).
First, using the HTML <form>
tag, you'll want to include enctype="multipart/form-data"
as an attribute.
Assuming you'll name your <input>
tag as myFile
(<form name="myFile">
), in your view, simply extract the file from request.FILES
:
def my_file_upload(request):
if request.method == 'POST':
myFile = request.FILES.get('myFile')
# At this point, myFile is an instance of UploadedFile, see
# https://docs.djangoproject.com/en/1.9/ref/files/uploads/ for details
Read up on uploaded files in the Django documentation to see the caveats associated with this approach.
Uploading a file to a webservice without saving to server, database, or locally
By the time your form action is invoked, ASP.NET has already done a lot of magic to interpret the file upload, so you can't really do much within the action itself. However, you can capture the byte streams in multipart forms as they come across the wire using an HttpModule or HttpHandler.
This example seems like it would be a good starting point.
I don't know whether an HttpRequest can begin returning data until after the payload has been received, so this is likely going to require some crazy cross-request magic if you literally want to "stream" the filtering process. On the other hand, if you were intending to keep the whole file in memory while you process it and then send it back afterward, I'd argue that you're better off allowing MVC to save the file as a temp file: you'd potentially get worse performance by keeping the entire uploaded file in memory while it's being uploaded.
Read file data without saving it in Flask
FileStorage
contains stream
field. This object must extend IO or file object, so it must contain read
and other similar methods. FileStorage
also extend stream
field object attributes, so you can just use file.read()
instead file.stream.read()
. Also you can use save
argument with dst
parameter as StringIO
or other IO or file object to copy FileStorage.stream
to another IO or file object.
See documentation: http://flask.pocoo.org/docs/api/#flask.Request.files and http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.
php FILE POST upload without save
If its text file (assuming size is not that huge) usually you could read it by
$contents= file_get_contents($_FILES['file']['tmp_name']);
If you are not sure which type of upload it was, check the request method
if(strtolower($_SERVER['REQUEST_METHOD'])=='post')
$contents= file_get_contents($_FILES['file']['tmp_name']);
elseif(strtolower($_SERVER['REQUEST_METHOD'])=='put')
$contents= file_get_contents("php://input");
else
$contents="";
Related Topics
How to Use Bundler Behind a Proxy
Need to Split Arrays to Sub Arrays of Specified Size in Ruby
Passing a Method as a Parameter in Ruby
In Rails, How to Add a New Method to String Class
How to Format the Value Shown in a Rails Edit Field
How to Test a Function With Gets.Chomp in It
Error Sudo: Gem: Command Not Found
Passing Parameters from View to Controller
Is Order of a Ruby Hash Literal Guaranteed
Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby
Ruby on Rails - Access Controller Variable from Model
How to Do Static Content in Rails
How to Sort an Array in Ruby to a Particular Order
Why Does White-Space Affect Ruby Function Calls
How to Check If a File Is Being Used by Other Application
Is the &Method(:Method_Name) Idiom Bad for Performance in Ruby