How to send a file through the REST API?

I am trying to send a file to the server through the REST API. The file could potentially be of any type, although it may be limited in size and type of things that can be sent as email attachments.

I think my approach would be to send the file as a binary stream and then save it back to the file when it arrives at the server. Is there a built-in way to do this in .Net or do I need to manually turn the contents of the file into a data stream and send it?

For clarity, I control the client and server code, so I am not limited to any specific approach.

+4
source share
4 answers

I would recommend you take a look at RestSharp
http://restsharp.org/

The RestSharp library has methods for placing files in the REST service. ( RestRequst.AddFile()). I believe that on the server side this translates to an encoded string in the body, with the content type in the header defining the file type.

I also saw this by converting the stream to a base-64 string and passing it as one of the properties of a serialized json / xml object. Especially if you can set size limits and want to include file metadata in the request as part of the same object, this works very well.

, . , , SO: RESTful?

+4

@MutantNinjaCodeMonkey RestSharp. webform jquery $.ajax web api. API . restsharp AddFile The request was aborted: The request was canceled. :

// Stream comes from web api HttpPostedFile.InputStream 
     (HttpContext.Current.Request.Files["fileUploadNameFromAjaxData"].InputStream)
using (var ms = new MemoryStream())
{
    fileUploadStream.CopyTo(ms);
    photoBytes = ms.ToArray();
}

var request = new RestRequest(Method.PUT)
{
    AlwaysMultipartFormData = true,
    Files = { FileParameter.Create("file", photoBytes, "file") }
};
+1
  • /, .
  • Determine the path where the file will be downloaded (and make sure that CHMOD 777 exists for this directory)
  • Accept client connection
  • Using a ready-made library for actual loading

Check out the following discussion: Downloading a REST file using HttpRequestMessage or Stream?

0
source

You can send it as a POST request to the server by transferring the file as FormParam.

    @POST
        @Path("/upload")
       //@Consumes(MediaType.MULTIPART_FORM_DATA)
        @Consumes("application/x-www-form-urlencoded")
        public Response uploadFile( @FormParam("uploadFile") String script,  @HeaderParam("X-Auth-Token") String STtoken, @Context HttpHeaders hh) {

            // local variables
            String uploadFilePath = null;
            InputStream fileInputStream = new ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8));

            //System.out.println(script); //debugging

            try {
                  uploadFilePath = writeToFileServer(fileInputStream, SCRIPT_FILENAME);
            }
            catch(IOException ioe){
               ioe.printStackTrace();
            }
            return Response.ok("File successfully uploaded at " + uploadFilePath + "\n").build();
        }

 private String writeToFileServer(InputStream inputStream, String fileName) throws IOException {

        OutputStream outputStream = null;
        String qualifiedUploadFilePath = SIMULATION_RESULTS_PATH + fileName;

        try {
            outputStream = new FileOutputStream(new File(qualifiedUploadFilePath));
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
            outputStream.flush();
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
        finally{
            //release resource, if any
            outputStream.close();
        }
        return qualifiedUploadFilePath;
    }
0
source

Source: https://habr.com/ru/post/1620412/


All Articles