java中使用restful web service来传输文件

Wesley13
• 阅读 868

【1】上传大文件:

前端页面:  
    1)同步上传:
        <html>  
            <body>  
                <form action="http://localhost:8081/webProject/api/file/uploadFile" method="post" enctype="multipart/form-data">  
                <input type="file" name="targetFile" />  
                <input type="text" name="userName" value="jxn" />  
                <input type="submit" value="提交" />  
                </form>  
            </body>  
        </html>  
  
    2)异步上传:
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="UTF-8">
                <title>异步上传文件</title>
            </head>
            <body>
                <form id= "uploadForm" >  
                      上传文件:    <input type="file" name="sendfile"/>
                                    <input type="button" value="上传" onclick="doUpload()" />  
                </form>  
                
                <script src="D:\soft\JQuery\jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script>
                <script type="text/javascript">
                    function doUpload() {  
                         // var formData = new FormData($("#uploadForm")[0]);  
                         var formData = new FormData()
                         formData.append("targetFile",$("#sendfile"));
                         formData.append("userName","test-username");
                         $.ajax({  
                              url: 'http://localhost:8081/webProject/api/file/uploadFile' ,  
                              type: 'POST',  
                              data: formData,  
                              async: false,  
                              cache: false,  
                              contentType: false,  
                              processData: false,  
                              dataType:'json',
                              success: function (data) {  
                                  alert(data);  
                              }
                         });  
                    }  
                </script>
            </body>
        </html>
      
      
后端:  
  
    web.xml  
        <servlet>  
            <servlet-name>CXFServlet</servlet-name>  
            <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
            <load-on-startup>1 </load-on-startup>  
        </servlet>  
        <servlet-mapping>  
            <servlet-name>CXFServlet</servlet-name>  
            <url-pattern>/api/*</url-pattern>  
        </servlet-mapping>  
  
    Spring配置文件:  
        <jaxrs:server id="restFileService" address="/file">  
            <jaxrs:providers>  
                <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />  
            </jaxrs:providers>  
            <jaxrs:serviceBeans>  
                <ref bean="restFileServiceImpl" />  
            </jaxrs:serviceBeans>  
        </jaxrs:server>  
          
        <bean id="restFileServiceImpl" class="xxx.api.fileprocess.REST.ApiFileProcessServiceImpl" />  
          
          
    接口:  
        import org.apache.cxf.jaxrs.ext.multipart.Attachment;  
        import org.apache.cxf.jaxrs.ext.multipart.Multipart;  
      
        @Path("")  
        public interface ApiFileProcessService {  
            [@POST](https://my.oschina.net/u/210428)  
            @Path("/uploadFile")  
            @Consumes(MediaType.MULTIPART_FORM_DATA)  
            public String uploadFile(@Multipart(value="targetFile")Attachment targetFile, @Multipart(value="userName")String userName);  
        }  
      
    实现:  
        import org.apache.cxf.jaxrs.ext.multipart.Attachment;  
        import javax.activation.DataHandler;  
      
        public class ApiFileProcessServiceImpl implements ApiFileProcessService {  
              
            @Override  
            public String uploadFile(Attachment targetFile, String userName) {  
                  
                try {  
                    DataHandler dataHandler = targetFile.getDataHandler();  
                    String originalFileName = new String(dataHandler.getName().getBytes("ISO8859-1"),"UTF-8");  
                    InputStream is = dataHandler.getInputStream();  
                      
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
                    String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName;  
                              
                    OutputStream out = new FileOutputStream(new File(saveLocation));  
                    int read = 0;  
                    byte[] bytes = new byte[4096];  
                    while ((read = is.read(bytes)) != -1) {  
                        out.write(bytes, 0, read);  
                    }  
                    out.flush();  
                    out.close();  
                      
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
                  
                return "success";  
            }  
        }  
          
    测试结果:可以轻松处理(上传)1G以上的文件。        

【2】上传小文件:

前端页面: 
    <html>
    <body>
        <form action="http://localhost:8081/webProject/api/file/uploadCommonFile" method="post" enctype="multipart/form-data">
        <input type="file" name="file1" />
        <input type="file" name="file2" />
        <input type="submit" value="提交" />
        </form>
    </body>
    </html>

后端:  
  
    接口: 
        import javax.ws.rs.core.Context;
        
        @Path("")  
        public interface ApiFileProcessService {  
            @POST
            @Path("/uploadCommonFile")
            @Consumes(MediaType.MULTIPART_FORM_DATA)
            public String uploadCommonFile(@Context HttpServletRequest request);
        }
        
    实现:
        import org.apache.commons.fileupload.FileItem;
        import org.apache.commons.fileupload.disk.DiskFileItemFactory;
        import org.apache.commons.fileupload.servlet.ServletFileUpload;
      
        public class ApiFileProcessServiceImpl implements ApiFileProcessService {  
            @Override
            public String uploadCommonFile(HttpServletRequest request) {

                try {
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    ServletFileUpload fileUpload = new ServletFileUpload(factory);
                    List<FileItem> items = fileUpload.parseRequest(request);

                    for (FileItem item : items) {
                        if (!item.isFormField()) {
                            String originalFileName = item.getName();
                            
                            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
                            String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName;  
                            
                            File picFile = new File(saveLocation);
                            item.write(picFile);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return "success";
            }
        } 


注意:此方法仅适合上传小文件。

【3】下载文件

case1:
    接口:    
        import javax.ws.rs.GET;
        import javax.ws.rs.QueryParam;

        @Path("")  
        public interface ApiFileProcessService {  
            @GET
            @Path("/downloadTemplate")
            public Response downloadTemplate(@QueryParam("templateName")templateName );
        }
        
    实现:
        import javax.ws.rs.core.Response;
        import javax.ws.rs.core.Response.ResponseBuilder;
        
        public class ApiFileProcessServiceImpl implements ApiFileProcessService {  
        
            @Override
            public Response downloadTemplate(String templateName) {

                File file = null;
                String fileName = null;
                
                try {
                    String applicationPath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();

                    file = new File(applicationPath + "/" + templateName);

                    fileName = URLEncoder.encode(templateName, "UTF-8"); // 如果不进行编码,则下载下来的文件名称是乱码
                    
                } catch (Exception e) {
                    e.printStackTrace();
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
                }
                
                ResponseBuilder response = Response.ok((Object) file);
                response.header("Content-Disposition", "attachment; filename=" + fileName);

                return response.build();
            }
        }
        
        
        
case2:    
    接口:
        
        import javax.ws.rs.*;
        import javax.ws.rs.core.Context;
        
        @GET
        @Path("/exportTest")
        @Produces("application/vnd.ms-excel")
        public Response exportTest(@FormParam("str") String str, @Context HttpServletResponse response);
        
    实现:
        import javax.ws.rs.core.Response;
        import javax.servlet.http.HttpServletResponse;
    
        @Override
        public Response exportTest(String str, HttpServletResponse response) {

            try {
                ServletOutputStream outputStream = response.getOutputStream();

                SXSSFWorkbook wb = new SXSSFWorkbook();
                wb.setCompressTempFiles(true);

                Sheet sheet = wb.createSheet("sheet0");
                Row row = sheet.createRow(0);
                row.createCell(0).setCellValue("hahaha");

                wb.write(outputStream);

                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("中文名字.xlsx", "UTF-8"));
                response.setContentType("application/vnd.ms-excel");
                outputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
点赞
收藏
评论区
推荐文章
待兔 待兔
3个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Easter79 Easter79
3年前
tp3.2读取excel文件
使用PHPExcel时,首先要下载PHPExcel并放在ThinkPHP/Library/Vendor下1.创建html文件(文件上传按钮)<formaction"{:U('控制器名/方法名')}"method"post"enctype"multipart/formdata" 
Stella981 Stella981
3年前
PHP导入导出EXCELl,CSV
PHP导入导出Excel,CSVHTML<formaction"{:U('Admin/Unit/importcsv')}"method"post"name"myform"id"myform"enctype"multipart/formdata"<input
Stella981 Stella981
3年前
Play 2.0 用户指南 - 文件上传 -- 针对Scala开发者
   处理文件上传   在form中指定multipart/formdata属性上传文件   上传文件的标准方式是指定form的一个特殊属性multipart/formdata,可以让你混合表单数据和表单文件附件。   开始编写HTML表单:@form(actionrou
Wesley13 Wesley13
3年前
PHP 表单
1、一个简单的HTML表单POSt方法包含两个输入字段和一个提交按钮<html<body<formaction"welcome.php"method"post"Name:<inputtype"text"name"name"<brEmail:<inputty
Wesley13 Wesley13
3年前
PHP 文件上传的原理及案例分析
原理将客户端文件上传至服务器端,在服务器端临时存储,再将服务器端临时存储的文件移至指定位置实现文件上传需要的知识点:前端页面1.form表单必须是用post发送方式,因为get会将参数带到url中,而上传的文件转换后字符会很长,而且也是为了安全性2.form表单需要使用enctype
Wesley13 Wesley13
3年前
PHP实现图片(文件)上传
这几天整理做过的php项目,感觉这个经常会用到,传上来共享一下咯首先,前端界面1、表单的首行需要加上enctype"multipart/formdata",需要上传的图片必须设置type"file"表示选择文件<formid"img_form"method"post"class"formhorizontal"r
Stella981 Stella981
3年前
Django
一:form表单标签的文件上传1:浏览器:html文件<h4form文件上传</h4<formaction"/file_put/"method"post"enctype"multipart/formdata"{%csrf_token
Stella981 Stella981
3年前
From表单提交的几种方式
<body<formaction"https://my.oschina.net/u/3285916"method"get"name"formOne"id"formId"name:<inputtype"text"name"name"pwd:<inputtyp
Stella981 Stella981
3年前
Jfinal文件上传
1\.给form添加enctype"multipart/formdata"属性,如下:<formid"form"action"/fileController/upload"method"post"enctype"multipart/formdata"<inputtype"file"name"f