传输格式基础知识

MIME 类型

MIME (Multipurpose Internet Mail Extensions) 是描述消息内容类型的因特网标准。

MIME 消息能包含文本、图像、音频、视频以及其他应用程序专用的数据。

MINE类型详细列表:https://www.w3school.com.cn/media/media_mimeref.asp

multipart/form-data

我们在通过 HTTP 向服务器发送 POST 请求提交数据,都是通过 form 表单形式提交的,如下:

<FORM method="POST" action="http://w.sohu.com/t2/upload.do" enctype="multipart/form-data"><INPUT type="text" name="city" value="Santa colo"><INPUT type="text" name="desc"><INPUT type="file" name="pic"></FORM>

提交时会向服务器端发出这样的数据

POST /t2/upload.do HTTP/1.1
User-Agent: SOHUWapRebot
Accept-Language: zh-cn,zh;q=0.5
Accept-Charset: GBK,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Content-Length: 60408
Content-Type:multipart/form-data; boundary=ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC
Host: w.sohu.com--ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC
Content-Disposition: form-data; name="city"Santa colo
--ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC
Content-Disposition: form-data;name="desc"
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit...
--ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC
Content-Disposition: form-data;name="pic"; filename="photo.jpg"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary... binary data of the jpg ...
--ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC--
  • application/x-www-urlencoded
  • multipart/form-data
  • text-plain

默认情况下是 application/x-www-urlencoded,当表单使用 POST 请求时,数据会被以 x-www-urlencoded 方式编码到 Body 中来传送, 而如果 GET 请求,则是附在 url 链接后面来发送。GET 请求只支持 ASCII 字符集,因此,如果我们要发送更大字符集的内容,我们应使用 POST 请求。

如果要发送大量的二进制数据(non-ASCII),"application/x-www-form-urlencoded" 显然是低效的。因此,这种情况下,应该使用 "multipart/form-data" 格式。

参考:https://www.jianshu.com/p/29e38bcc8a1d

代码实现

依赖

        <dependency><groupId>org.glassfish.jersey.media</groupId><artifactId>jersey-media-multipart</artifactId><version>2.33</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.11.0</version></dependency>

接口实现

package com.jsq.hibernate.resource;import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.*;
import java.util.Map;@Path("file")
@Slf4j
@Produces(MediaType.APPLICATION_JSON)
public class FileResource {@POST@Path("upload")@Consumes(MediaType.MULTIPART_FORM_DATA)public Response uploadFile(@Context HttpServletRequest request,@FormDataParam("file") InputStream inputStream,@FormDataParam("file") FormDataContentDisposition formDataContentDisposition) {log.info("start tp upload");Map<String, String> parameters = formDataContentDisposition.getParameters();log.info("parameters is {}", parameters);String fileName = formDataContentDisposition.getFileName();String path = "D:";File file = new File(path + File.separator + fileName);try (FileOutputStream outputStream = FileUtils.openOutputStream(file);BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {IOUtils.copy(inputStream, bufferedOutputStream, 8192);return Response.ok().entity(ImmutableMap.of("code", 0, "message", "success")).build();} catch (IOException e) {return Response.ok().type(MediaType.APPLICATION_JSON).entity(ImmutableMap.of("code", 0, "message", e.getMessage())).build();}}@GET@Path("download")public Response downloadFile(@QueryParam("filename") String filename, @Context HttpServletRequest request) {Map<String, String[]> parameterMap = request.getParameterMap();log.info("parameters of request is {}", parameterMap);String path = "D:";File file = new File(path + File.separator + filename);if (!file.exists()) {return Response.ok().entity(ImmutableMap.of("code", 1, "message", "file does not exist")).build();}return Response.ok().entity(file).header("Content-disposition", "attachment;filename=" + filename).header("Cache-Control", "no-cache").build();}@GET@Path("download/stream")public Response downloadStream(@QueryParam("filename") String filename, @Context HttpServletRequest request) throws IOException {Map<String, String[]> parameterMap = request.getParameterMap();log.info("parameters of request is {}", parameterMap);String path = "D:";File file = new File(path + File.separator + filename);if (!file.exists()) {return Response.ok().entity(ImmutableMap.of("code", 1, "message", "file does not exist")).build();}return Response.ok().entity(new StreamingOutput() {@Overridepublic void write(OutputStream output) throws IOException, WebApplicationException {output.write(FileUtils.readFileToByteArray(file));}}).header("Content-disposition", "attachment;filename=" + filename).header("Cache-Control", "no-cache").build();}
}

上传文件

  1. @Consumes(MediaType.MULTIPART_FORM_DATA),消费的是表单样式

  2. @Produces(MediaType.APPLICATION_JSON),返回的响应是json样式

  3. 输入参数:@FormDataParam("file") InputStream inputStream,文件流

  4. 输入参数:@FormDataParam("file") FormDataContentDisposition formDataContentDisposition,文件相关信息

  5. 将输入的流转化为文件存于本地

  6. postman操作

下载文件

  1. 两种下载文件的方式:文件形式和流的形式
  2. 响应头中放入"Content-disposition", "attachment;filename=" + filename,**Content-Disposition**响应标头是指示内容是否预期在浏览器中内联显示的标题,即,作为网页或作为网页的一部分或作为附件下载并且本地保存
  3. header中相关知识点见:https://cloud.tencent.com/developer/section/1189916

启动类

package com.jsq.hibernate;import com.jsq.hibernate.config.HelloWorldConfiguration;
import com.jsq.hibernate.resource.FileResource;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.glassfish.jersey.media.multipart.MultiPartFeature;import java.net.URL;public class HelloWorldApplication extends Application<HelloWorldConfiguration> {public static void main(String[] args) throws Exception {URL yml = HelloWorldApplication.class.getClassLoader().getResource("server.yml");String configFile = yml.getFile();System.out.println(configFile);args = new String[]{"server", configFile};new HelloWorldApplication().run(args);}@Overridepublic void run(HelloWorldConfiguration helloWorldConfiguration, Environment environment) {environment.jersey().register(new MultiPartFeature());environment.jersey().register(new FileResource());}@Overridepublic String getName() {return "hello-world";}@Overridepublic void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {      }
}

注:

  1. MultiPartFeature必须注册
  2. 注册Resource类

dropwizard中上传和下载文件相关推荐

  1. java上传和下载文件代码_JavaWeb中上传和下载文件实例代码

    一丶先引入上传下载的lib 二丶上传的的servlet package com.test.action; import java.io.file; import java.io.fileoutputs ...

  2. Python实现向s3共享存储上传和下载文件

    Python实现向s3共享存储上传和下载文件 https://www.cnblogs.com/liang545621/p/10298617.html 使用Python从S3上传和下载文件 https: ...

  3. windows主机用scp命令向Linux服务器上传和下载文件

    windows主机用scp命令向Linux服务器上传和下载文件 文章目录: 一.scp介绍 二.scp上传和下载 1.上传 2.下载 三.scp的更多参数 一.scp介绍 scp是secure cop ...

  4. 利用SecureCRT上传、下载文件(使用sz与rz命令)

    利用SecureCRT上传.下载文件(使用sz与rz命令) 借助securtCRT,使用linux命令sz可以很方便的将服务器上的文件下载到本地,使用rz命令则是把本地文件上传到服务器. 其中,对于s ...

  5. 从服务器上传和下载文件方法

    1. ssh 安装SSH Secure Shell Client客户端 下载链接 http://download.csdn.net/detail/jiandanjinxin/9755684 使用方法参 ...

  6. Linux--用SecureCRT来上传和下载文件

    转载自  Linux--用SecureCRT来上传和下载文件 SecureCRT下的文件传输协议有以下几种:ASCII.Xmodem.Ymodem.Zmodem ASCII:这是最快的传输协议,但只能 ...

  7. java http 下载文件_JAVA通过HttpURLConnection 上传和下载文件的方法

    本文介绍了JAVA通过HttpURLConnection 上传和下载文件的方法,分享给大家,具体如下: HttpURLConnection文件上传 HttpURLConnection采用模拟浏览器上传 ...

  8. linux securefx 传输文件失败,解惑:如何使用SecureCRT上传和下载文件、SecureFX乱码问题...

    解惑:如何使用SecureCRT上传和下载文件.SecureFX乱码问题 一.前言 很多时候在windows平台上访问Linux系统的比较好用的工具之一就是SecureCRT了,下面介绍一下这个软件的 ...

  9. Linux下rz/sz安装及使用方法_上传和下载文件

    2019独角兽企业重金招聘Python工程师标准>>> Linux下rz/sz安装及使用方法_上传和下载文件 转载于:https://my.oschina.net/276172622 ...

最新文章

  1. 深度优先搜索找迷宫的出路
  2. 2021-04-05 Python tqdm显示代码任务进度
  3. 算法-Valid Anagram
  4. vscode快捷键大全
  5. .net MySQL事物_在ASP.NET 2.0中操作数据之六十一:在事务里对数据库修改进行封装...
  6. 活动目录域结构和域信任关系建立实验
  7. HDU1312 Red and Black(dfs+连通性问题)
  8. 为什么用java开发app_安卓开发为什么选择用Java语言
  9. Tnpsp创业项目计划将与阿里巴巴展开全面竞争!
  10. 转载:Spring使用p名称空间配置属性
  11. CentOS中nginx负载均衡和反向代理的搭建
  12. 使用存储过程备份SqlServer数据库
  13. VC++进行ActiveX控件的开发
  14. caj文件转pdf、QQ文件、微信视频
  15. 重点人员动态管控系统开发,公安情报研判分析平台建设
  16. Spark Sql编程
  17. C++特征码查找 附加案例
  18. 视频二维码在线生成器怎么用?
  19. 谈谈我对元宇宙的理解
  20. JS 案例 树形菜单

热门文章

  1. 安卓---第5章 数据存储---保存QQ账号与密码
  2. c++实现定时向qq好友发送消息
  3. 【C++学习笔记】3.第一个程序与注释
  4. java的下载地址_java资源下载之官网地址
  5. 常见企业级搜索服务器
  6. 网络丢包工具clumsy
  7. 基于硬件的C(C++)语言程序设计教程4:计算货款
  8. Go语言开发Web程序
  9. java redis密码_Redis 密码设置和查看密码
  10. 第44届ICPC国际大学生程序设计亚洲区域赛(南京站)心得体会