Upload files to webservers using Matlab's webread/webwrite or urlread2, urlreadpost

11 vues (au cours des 30 derniers jours)
vaibhav
vaibhav le 17 Juil 2015
Réponse apportée : Vinod le 14 Oct 2016
Hi, I am trying to upload a file to a webserver using an api. I can read the contents of the file to a string (using fileread) and then pass that to the api (see expected api payload below). I have used Matlab's in-built functions (webread, webwrite for accessing APIs), urlread2 and urlreadpost but havent been successful. I modified the code in urlreadpost.m:
urlConnection.setDoOutput(true);
boundary = '---------------------------';%'BoUnDaRyStRiNg';%'***********************';
urlConnection.setRequestProperty( ...
'Content-Type',['multipart/form-data; boundary=',boundary]);
printStream = java.io.PrintStream(urlConnection.getOutputStream);
% also create a binary stream
% dataOutputStream = java.io.DataOutputStream(urlConnection.getOutputStream);
eol = [char(13),char(10)];
for i=1:2:length(params)
printStream.print(['--',boundary,eol]);
printStream.print(['Content-Disposition: form-data; name="',params{i},'"']);
if ischar(params{i+1})
% binary data is uploaded as an octet stream
% Echo Nest API demands a filename in this case
printStream.print(['; filename="file.wrg"',eol]);
printStream.print(['Content-Type: application/octet-stream',eol]);
printStream.print(params(i+1))
printStream.print([eol]);
%dataOutputStream.write(params{i+1},0,length(params{i+1}));
printStream.print([eol]);
else
disp('Hello')
printStream.print([eol]);
printStream.print([eol]);
printStream.print([params{i+1},eol]);
end
end
% printStream.print(['--',boundary,'--',eol]);
printStream.close;
The expected the request payload for the API should look like this.
-----------------------------147542583027268
Content-Disposition: form-data; name="wrg_file"; filename="Breivikfjellet_windoku.wrg"
Content-Type: application/octet-stream
14 11 606338 7140563 373
GridPoint 606338 7140563 200 80 4.51 2.000 0 12 80 45 200 80 45 200 80 45 200 80 45 200 80 45 200 80 45 200 80 45 200 80 45 200 80 45 200 80 45 200 80 45 200 80 45 200
....
GridPoint 611187 7144293 200 80 9.03 2.000 0 12 80 90 200 80 90 200 80 90 200 80 90 200 80 90 200 80 90 200 80 90 200 80 90 200 80 90 200 80 90 200 80 90 200 80 90 200
-----------------------------147542583027268--
  2 commentaires
Eugene
Eugene le 6 Avr 2016
Did you find and answer to your question? I've got the same problem and had to use urlreadpost instead of the native webwrite.
Alex
Alex le 6 Mai 2016
Please upvote this question!

Connectez-vous pour commenter.

Réponses (1)

Vinod
Vinod le 14 Oct 2016
Here's an example that uploads any file from MATLAB to DropBox programmatically:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by