• File Upload with Jersey


    package com.toic.rest;
     
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.ws.rs.Consumes;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import com.sun.jersey.core.header.FormDataContentDisposition;
    import com.sun.jersey.multipart.FormDataParam;
    
    @Path("/file")
    public class UploadFileService {
    
        @POST
        @Path("/upload")
        @Consumes(MediaType.MULTIPART_FORM_DATA)
        public Response uploadFile(
                @FormDataParam("file") InputStream uploadedInputStream,
                @FormDataParam("file") FormDataContentDisposition fileDetail) {
    
            String uploadedFileLocation = "d://uploaded/"+ fileDetail.getFileName();
    
            // save it
            writeToFile(uploadedInputStream, uploadedFileLocation);
    
            String output = "File uploaded to : " + uploadedFileLocation;
    
            return Response.status(200).entity(output).build();
    
        }
    
        // save uploaded file to new location
        private void writeToFile(InputStream uploadedInputStream,
                String uploadedFileLocation) {
    
            try {
                OutputStream out = new FileOutputStream(new File(
                        uploadedFileLocation));
                int read = 0;
                byte[] bytes = new byte[1024];
    
                out = new FileOutputStream(new File(uploadedFileLocation));
                while ((read = uploadedInputStream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                out.flush();
                out.close();
            } catch (IOException e) {
    
                e.printStackTrace();
            }
    
        }
    
    }
    <!DOCTYPE html>
    <html>
    <body>
        <h1>File Upload with Jersey</h1>
     
        <form action="http://localhost:7001/RESTfull001/file/upload" method="post" enctype="multipart/form-data">
     
           <p>
            Select a file : <input type="file" name="file" size="45" />
           </p>
     
           <input type="submit" value="Upload It" />
        </form>
     
    </body>
    </html>
  • 相关阅读:
    揭秘数字行为:快速地多次点击
    MySQL事务在MGR中的漫游记—路线图
    如何成为一名获客专家?
    10分钟快速构建汽车零售看板
    聊一聊整车厂的那些事——售后配件业务
    网易云易盾牵手百视通 助力广电领域新媒体内容安全
    人工智能热门图书(深度学习、TensorFlow)免费送!
    dubbo异步调用原理 (1)
    dubbo事件通知机制 (2)
    dubbo事件通知机制(1)
  • 原文地址:https://www.cnblogs.com/rojas/p/4626839.html
Copyright © 2020-2023  润新知