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

【1】上传大文件:

前端页面:

1)同步上传:

2)异步上传:

异步上传文件

上传文件:

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);

}

});

}

后端:

web.xml

CXFServlet

org.apache.cxf.transport.servlet.CXFServlet

1

CXFServlet

/api/*

Spring配置文件:

接口:

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】上传小文件:

前端页面:

后端:

接口:

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 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;

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/556077.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

enum与int、String之间的转换

enum与int、String之间的转换 enum<->int enum -> int: int i enumType.value.ordinal(); int -> enum: enumType b enumType.values()[i]; enum<->String enum -> String: enumType.name() String -> enum: enumType.valueOf(name); 下面是Enum和字…

ios 简书 获取通讯录信息_iOS-授权获取通讯录

- (void)getContact{CNAuthorizationStatus authorizationStatus [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];if(authorizationStatus CNAuthorizationStatusAuthorized) {// 获取指定的字段,并不是要获取所有字段&#xff0c;需要指定具体的字…

枚举ENUM的tostring() valueof()name()和values()用法

从jdk5出现了枚举类后,定义一些字典值可以使用枚举类型; 枚举常用的方法是values():对枚举中的常量值进行遍历; valueof(String name) :根据名称获取枚举类中定义的常量值;要求字符串跟枚举的常量名必须一致; 获取枚举类中的常量的名称使用枚举对象.name() 枚举类中重写了t…

Vue键盘事件

<!--1. Vue 中常用的按键别名&#xff1a;回车 > enter删除 > delete (捕获"删除"和"退格"键&#xff09;退出 > esc空格 > space换行 > tab &#xff08;特殊&#xff0c;必须配合 keydown 去使用&#xff09;上 > up下 > down左…

win10引导安卓x86_生命不息折腾不止 Win10竟与安卓有一腿

有些公司、有些产品、有些人总是生命不息折腾不止&#xff0c;不断地更新补丁、不断地出现新的漏洞。近日&#xff0c;微软又搞了几个大新闻。微软Azure营收翻倍&#xff1a;月初&#xff0c;微软重组其销售团队&#xff0c;更专注于云服务的提供&#xff0c;而其销售工作将会转…

Vue 计算属性 computed

<!--计算属性&#xff1a;1. 定义&#xff1a;要用的属性不存在&#xff0c;要通过已有的属性计算得来2. 原理&#xff1a;底层借助了 Object.defineProperty 方法提供的 getter 和 setter3. get 函数什么时候执行&#xff1f;(1). 初次读取时会执行一次(2). 当依赖的数据发…

Mysql 数据库默认值选 ‘‘“ 、Null和Empty String的区别

Mysql 数据库默认值选 ‘’" 、Null和Empty String的区别 1&#xff1a;空值(’’)是不占用空间的 2: MySQL中的NULL其实是占用空间的。官方文档说明: “NULL columns require additional space in the row to record whether their values are NULL. For MyISAM tables,…

Vue 监视属性 watch

<!--监视属性 watch:1. 当被监视的属性变化时&#xff0c;回调函数自动调用&#xff0c;进行相关操作2. 监视的属性必须存在&#xff0c;才能进行监视3. 监视的两种写法&#xff1a;(1). new Vue 时传入 watch 配置(2). 通过 vm.$watch 监视深度监视&#xff1a;(1). Vue 中…

NAVICAT MYSQL 建表字段 默认值、EMPTY STRING、空白、NULL 的区别

Navicat mysql 建表字段 默认值、empty string、空白、NULL 的区别 总结在最后&#xff0c;没啥干货 简单测试了4种类型 bigint tinyint varchar char 单引号 ‘’ 双引号 “” 自定义的默认值 如&#xff1a; 未知的姓名 新建一张用户表 CREATE TABLE user (id bigint(20…

ddr2的上电顺序_关于内存的插入顺序的问题

展开全部#ifndef FUNS_H#define FUNS_Hvoid error( char *, ... ); /* 输出错误信32313133353236313431303231363533e59b9ee7ad9431333234323734息&#xff0c;退出程序 */void flush_stdin( void ); /* 清空“输入缓冲区” */#endif#ifndef SQLIST_H#define SQLIST_H#define I…

如何将vue项目打包为.apk文件

说明&#xff1a;使用Vue.js开发完毕的app一般不作处理的话&#xff0c;就只能在浏览器上做为Webapp使用。如果需要将它安装到安卓手机上就需要打包为.apk文件了。 前提&#xff1a;安装HBuilderX 具体步骤&#xff1a; 1.在vue项目中找到config/build.js 2.找到build下的a…

vue 样式绑定 class

<!--绑定样式&#xff1a;1. class 样式写法&#xff1a;:class"xxx" xxx 可以是字符串、对象、数组字符串写法适用于&#xff1a;类名不确定&#xff0c;要动态获取对象写法适用于&#xff1a;要绑定多个样式&#xff0c;个数不确定&#xff0c;名字也不确定数组…

python web后端和vue哪个难_全栈开发用纯后端模板与Vue+后端框架组合哪个好?

全栈开发没有明确的定义&#xff0c;但应该指的就是前端后端数据库。所以只用纯后端框架&#xff0c;不算全站开发。至少在Angularjs出现以前&#xff0c;我没听说过全站开发这个词。你问题描述中的感觉是对的&#xff0c;这就是前后端分离的好处。前后端分离就是&#xff1a;两…

MySQL 字段默认值该如何设置

MySQL 字段默认值该如何设置 前言&#xff1a; 在 MySQL 中&#xff0c;我们可以为表字段设置默认值&#xff0c;在表中插入一条新记录时&#xff0c;如果没有为某个字段赋值&#xff0c;系统就会自动为这个字段插入默认值。关于默认值&#xff0c;有些知识还是需要了解的&am…

vue 条件渲染 v-if | v-show

<!--条件渲染&#xff1a;1. v-if写法&#xff1a;(1). v-if"表达式"(2). v-else-if"表达式"(3). v-else"表达式"适用于&#xff1a;切换评率较低的场景特点&#xff1a;不展示的DOM元素直接被移除注意&#xff1a;v-if 可以和 v-else-if、v-…

unity摄影机depth模式_Unity3D Camera 摄像机属性详解

unity3d摄像机参数1.ClearFlags:清除标记。决定屏幕的哪部分将被清除。一般用户使用对台摄像机来描绘不同游戏对象的情况&#xff0c;有3中模式选择&#xff1a;Skybox&#xff1a;天空盒。默认模式。在屏幕中的空白部分将显示当前摄像机的天空盒。如果当前摄像机没有设置天空盒…

mysql,in中重复的记录也查出的方法

mysql&#xff0c;in中重复的记录也查出的方法 如题&#xff0c;举例说明下&#xff0c;假如where in (1,2,3,2,5,3);其中2&#xff0c;3都有重复的&#xff0c;想要让查出的记录数量和in中的相同&#xff0c;重复的也会显示重复的记录&#xff0c;就是得出的记录是6条。 in有…

vue 列表渲染 v-for

一、v-for 基本使用 <!--v-for 指令1. 用于展示列表数据2. 语法&#xff1a;v-for"(item, index) in xxx" :key"yyy"3. 可遍历&#xff1a;数组、对象、字符串&#xff08;用得少&#xff09;、指定次数&#xff08;用得少&#xff09; --> <div…

nginx 上传 文件超时设置_nginx限制上传大小和超时时间设置说明/php限制上传大小...

现象说明&#xff1a;在服务器上部署了一套后台环境&#xff0c;使用的是nginx反向代理tomcat架构&#xff0c;在后台里上传一个70M的视频文件&#xff0c;上传到一半就失效了&#xff01;原因是nginx配置里限制了上传文件的大小client_max_body_size&#xff1a;这个参数的设置…

Mysql 5.7 的‘虚拟列’是做什么?

Mysql 5.7 中推出了一个非常实用的功能 虚拟列 Generated (Virtual) Columns 对于它的用途&#xff0c;我们通过一个场景来说明 假设有一个表&#xff0c;其中包含一个 date 类型的列 SimpleDate dateSimpleDate 是一个常用的查询字段&#xff0c;并需要对其执行日期函数&a…