I have a few questions regarding uploading files to a HTTp request (from an applet). This is what I am following:
I am taking a screenshot of the screen using Applet's robot and storing the same on the local file system. The file I have saved on the local file system needs to be uploaded to Apache, eventually to be accessed by PHP.
public void sendBufferedImage(File file, BufferedImage screenImage, String urlPath) throws Exception
{
ImageIO.write(screenImage, "GIF", file); // This is to store the file in
a temp location on the local file system.
url = new URL(urlPath);
urlcon = (HttpURLConnection) url.openConnection();
urlcon.setRequestMethod("POST");
urlcon.setDoOutput(true);
urlcon.connect();
out = new DataOutputStream(urlcon.getOutputStream());
out.write(file.getPath().getBytes());
}
Does this complete writing the file to the HTTP request?
If so, how should reading the HTTP request work to get the file handle out of the byte array written to the HTTP request?
Can a file be written to the HTTP request only via byte array?
A sample of how the php code would look like while getting the file handle out of the HTTP request would help a great deal.
Thanks,
Related
I was wondering if any one can help with following issue.
I have an Api with node/express for image uploads
server1
var upload = multer({ dest: 'uploads/'})
app.post('/api/upload', upload.single('file'), function(req, res, next) {
if (req.file && req.file.path) {
//used to have imgur upload
//imgur.uploadFile(req.file.path)
// .then(function (json) {
//});
}
});
server2
I have PHP Api for image uploads as well which I have set up for self-hosting using pictshare. I want to redirect file uploads to new API by redirecting uploads to PHP Api server.
Have tried multer, multiparty, needle, request and various other methods... but somehow couldn't figure out.
Is there way to direct multer to new destination?
File is being saved in uploads/ folder, maybe better would be to upload/direct that file to new server and return new url from server2 ?
Looked around for pipelining upload images, with not much luck..
note: server1 api is being used by mobile app so wouldn't want to release app update if it can be handled from server side.
To upload a file (image or whatever) you need to have it in your drive first (or in memory, but I will tackle the drive case first). Then you can read it and send it.
The APIs that receive files use to receive forms. Usually they expect to receive a form where the attachment comes as a file field.
Here you can see a working example uploading an existing file in my drive to an external API by using the 'superagent' library for Node.
const
fs = require('fs'),
agent = require('superagent');
const stream = fs.createReadStream('path/to/downloaded/file');
agent.post(`urlOfApi/uploadFileEndpoint`)
.type('form')
.attach('file', stream.path);
Currently I'm creating an app using IntelXDK to upload image from devices to my server.
The problem currently I'm encountering is, how to code my backend so that it can receive the upload file from mobile device?
In PHP, I only know that the file upload requires:
<input type="file" name="file" />
then use $FILES["file"] to save it into storage
And is almost similar in .Net as well.
But I'm still couldn't think of how to receive the file once it is uploaded via mobile.
Would be great if someone share or advise the missing part (.Net and PHP).
In ASP.net server side use webservice receive in byte format and save that as you want.
Code sample refrence link http://www.codeproject.com/Articles/22985/Upload-Any-File-Type-through-a-Web-Service
[WebMethod]
public string UploadFile(byte[] f, string fileName)
{
// the byte array argument contains the content of the file
// the string argument contains the name and extension
// of the file passed in the byte array
try
{
// instance a memory stream and pass the
// byte array to its constructor
MemoryStream ms = new MemoryStream(f);
// instance a filestream pointing to the
// storage folder, use the original file name
// to name the resulting file
FileStream fs = new FileStream
(System.Web.Hosting.HostingEnvironment.MapPath
("~/TransientStorage/") +
fileName, FileMode.Create);
// write the memory stream containing the original
// file as a byte array to the filestream
ms.WriteTo(fs);
// clean up
ms.Close();
fs.Close();
fs.Dispose();
// return OK if we made it this far
return "OK";
}
catch (Exception ex)
{
// return the error message if the operation fails
return ex.Message.ToString();
}
}
}
}
For more information about uploading files to a server: https://software.intel.com/en-us/node/493213
If you are aware of ASP.NET Web API 2, have a look at this sample:
http://aspnet.codeplex.com/sourcecontrol/latest#Samples/WebApi/FileUploadSample/
Also, check these ones:
http://damienbod.wordpress.com/2014/03/28/web-api-file-upload-single-or-multiple-files/
http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2
http://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/
Check these SO links:
How To Accept a File POST
File upload Jquery WebApi
I think, with above links, you will be surely able to create service that intakes file uploaded from a form.
Hope it helps you...
All the best...
Use Case: I am working on an image uploader which uses ajax upload function.I want to upload images to a subdomain user creates on the website.For example,when the user creates a domain on the website I copy a php script for uploading images to the new domain viz image-cropping.php.I want to send a request to this file when the user uploads any image to his domain.
Issue:When I try to upload an image I get Error: Permission denied to access property 'readyState'.My calling js file is on xyz.google.com and the upload php script is on abc.google.com.
Research
After doing some googling and research I learnt javascript won't allow to send request cross domain and it needs a http proxy to handle this.Here is the code I have tried.The script to run the ajax uploader.In action I have the path to file on other domain(the path is built dynamically).
new AjaxUpload(btnUpload, {
action: 'includes/modules/domain_creation/proxy.php',
name: 'image',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif|JPG|JPEG|PNG|GIF)$/.test(ext))){
alert('Only JPG, PNG or GIF files are allowed');
return false;
}
$('#thumbImg').html('<img src="http://localhost/gobiggi_VS_2_2/images/appImages/imageLoader.png" />');
},
1) Am I doing it in the right way(working on it for first time)?Is the proxy actually needed?2)How and where can I set the proxy so that the error permission can be negotiated?3)What security issues does it open up(Is it safe?If not what's an alternative)?Any pointers or suggestions would be helpful for me.Thank you for your time.
Update:
I am using this proxy script for uploading the image.Part of the code is
$domainUsername = $_SESSION['domainUsername'];
$domainNameWeb = $_SESSION['domainName'];
//$fileParameterProxy = $_FILES['image'];
//Destination URL: Where this proxy leads to the upload script
$destinationURL = 'http://www.'.$domainNameWeb.'/'.$domainUsername.'/upload.php';
//The only domain from which requests are authorized.
$RequestDomain = 'abc.net';
Now I don't get the Error for permission but I am not able to get the image on to the server.When I try to do print_r($_FILES) I get a blank array on my upload script.
I believe I am missing something!!Can someone please correct?
Thank you for your time!
1 and 2) You have to set your proxy as action, because that is the place where you are allowed to upload the files. The proxy then will do the request to the other domain, where it can send the files to.
3) Depends on your proxy implementation. You should avoid to store the files locally or execute/include anything from user input, like always when writing php scripts. Directly send the tmp file to your destination server, this will also be the fastest implementation.
I have been trying to upload a file to a webserver using LUA.
My problem is that I want to upload a file using LUA to webserver which mimics uploading a file like from a browser.
I was successfully able to upload file using server, where I can do file_get_contents('php://input'), where i get contents and mime_decode on it and save that file.
But, i want to achieve where i can do like $_FILES['file_name'], on server side using lua.
so does anybody have idea how to do this in LUA?
Regards.
You can use the HTTP sockets library for sending HTTP requests and ltn12 library for filters (file input). Both should be provided with Lua.
http = require("socket.http")
ltn12 = require("ltn12")
http.request{
url = "url://to.server/upload/script.php",
method = "POST",
headers = {
["Content-Type"] = "multipart/form-data",
["Content-Length"] = sizeOfFile
},
source = ltn12.source.file(io.open(pathToLocalFile)),
sink = ltn12.sink.table(response_body)
}
print(response_body[1]) --response to request
this should be real quick. Currently I have this code to write an image to an output stream and upload it to a server:
OutputStream os = connection.getOutputStream();
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
int totalBytes = fis.available();
for(int i = 0; i < totalBytes; i++) {
os.write(fis.read());
}
Etc. (I know that for loop for writing the data is super basic, I'm gonna make it a bit better in the future I'm just trying to get things working at a basic level here).
Anyways, as you can see I'm writing a file to the stream and sending it out, this works just fine. My problem is, I have no way as of yet to transmit the proper file name as well. On the php end I just set it to a generic timestamp file name, and I don't want to use the default image name on the phone either, the image uploaded will include the user's name who uploaded, including a timestamp which I can add on the php end just fine. I just need to know how to include something like a namevaluepair which has the user's name in it, so on the php side the filename can include that string. Thanks!
edit: dont know why i was saying data, its just an output stream...
The file name is usually sent in the headers. For POST (which is usually what you are using when you obtain an output stream), you should have a content-type of multipart/form-data and each part will have a content-disposition header. For a part corresponding to the file (the only part, in your case), the content-disposition header should have a filename="foo.txt" component. The server then saves the contents in a temp file and hands your script the info contained in the content-disposition header (along with a means of getting to the uploaded file itself).
See RFC 1867 for details.