非常に詳細なファイルのアップロードとダウンロード
序論Ⅰ: @RequestParam と @RequestPart の違い
@RequestPart
@RequestPart
このアノテーションは、multipart/form-data
フォーム送信リクエスト メソッドで使用されます。- サポートされているリクエスト メソッド メソッドは、
MultipartFile
SpringMultipartResolver
クラスに属します。このリクエストは経由でhttp协议
送信されます
@RequestParam
@RequestParam
サポートapplication/json
、およびサポートmultipart/form-data
リクエスト
コードのデモ
-
テスト 1: @RequestPart を使用して json データを受信する
結論:に変換
@RequestPart
できますjsonData
json数据
Person对象
/** * 测试 RequestParam 和 RequestPart区别2 * @param person * @param file1 * @return * @throws IOException * @throws ServletException */ @RequestMapping(value = "/upload3",method = RequestMethod.POST) @ResponseBody public String readFile1(@RequestPart("person") Person person , @RequestPart("file1") MultipartFile file1) { StringBuilder sb = new StringBuilder(); sb.append(file1.getOriginalFilename()).append(";;;"); return person.toString() + ":::" + sb.toString(); }
パラメータ名 パラメータ値 パラメータタイプ ファイル1 ファイル ファイル 人 {"name":"cvzhanshi","age":23} アプリケーション/json テスト結果: オブジェクトを使用して json を受け取ることができます
-
テスト 2: @RequestParam を使用して json データを受信する
結論:受信のみに
@RequestParam
使用jsonData
json数据
String字符串
/** * 测试 RequestParam 和 RequestPart区别2 * @param person * @param file1 * @return * @throws IOException * @throws ServletException */ @RequestMapping(value = "/upload3",method = RequestMethod.POST) @ResponseBody public String readFile1(@RequestParam("person") Person person , @RequestPart("file1") MultipartFile file1) { StringBuilder sb = new StringBuilder(); sb.append(file1.getOriginalFilename()).append(";;;"); return person.toString() + ":::" + sb.toString(); }
测试結果:报错 2022-10-08 10:19:48.434 WARN 3440 — [nio-8888-exec-1] .wsmsDefaultHandlerExceptionResolver : 解決済み [org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type] 「java.lang.String」を必要なタイプ「cn.cvzhanshi.test.entity.Person」に。ネストされた例外は java.lang.IllegalStateException:タイプ 'java.lang.String' の値を必要なタイプ 'cn.cvzhanshi.test.entity.Person' に変換できません:一致するエディターまたは変換戦略が見つかりません]
エラーの説明: 文字列型のみを受信して解析します
違い(まとめ)
- リクエスト時に受け取ることができる値のみ、複雑なリクエスト フィールド (など)
multipart/form-data
を受け取ることができます。@RequestParam
String类型
name-value
@RequestPart
json、xml
@RequestParam
Converter or PropertyEditor
データ分析による、@RequestPart
参照'Content-Type' header
、HttpMessageConverters
データ分析による- リクエストヘッダーに Content-Type: multipart/form-data を指定した場合、渡されたjsonパラメータ、 @RequestPart アノテーションはオブジェクトで受信可能、 @RequestParam は文字列でのみ受信可能
- @RequestParam は name-valueString 型のリクエスト フィールドに適しており、 @RequestPart は複雑なリクエスト フィールド (JSON、XML など) に適しています; これらの最大の違いは、リクエスト メソッドのリクエスト パラメータの型が String ではなくなった場合です。タイプ
序文Ⅱ: getParameter() と getPart() の違い
コードのテスト
/**
* 测试 RequestParam 和 RequestPart区别1
* @param request
* @param name
* @param file1
* @return
* @throws IOException
* @throws ServletException
*/
@RequestMapping(value = "/upload1",method = RequestMethod.POST)
@ResponseBody
public String readFile(HttpServletRequest request,@RequestParam("name") String name ,@RequestPart("file1") MultipartFile file1) throws IOException, ServletException {
String ageParameter = request.getParameter("age");
Part agePart = request.getPart("age");
String file2Parameter = request.getParameter("file2");
Part file2Part = request.getPart("file2");
Enumeration<String> parameterNames = request.getParameterNames();
Collection<Part> parts = request.getParts();
return "";
}
パラメータを渡す
鍵 | 価値 | タイプ |
---|---|---|
名前 | ツザンシ | 文章 |
年 | 18 | 文章 |
ファイル1 | 新しいテキスト document.txt | ファイル |
ファイル2 | 美しさ.jpg | ファイル |
デバッグ分析:
-
request : リクエストには 2 つの Parameter パラメーターと 2 つの Part パラメーターがあることがわかります
-
Parameter and Part : request.getParameter で取得した値と request.getPart で取得した値
request.getParameter() を使用してファイル タイプ パラメータを取得することは空であり、request.getPart() を使用して非ファイル タイプを取得することは空です。
-
ParameterNames と Parts : getParameterNames() と getParts() はパラメーター名を取得します
結果: request.getParameterNames() を使用してファイル タイプ以外のパラメーター名のみを取得し、request.getParts() を使用してすべてのパラメーター名を取得します。
結論は
- Part はすべてのリクエスト パラメータのパラメータ名を取得できますが、Parameter はファイル タイプ以外のパラメータ名のみを取得できます。
- パーツはファイル タイプ以外のパラメーターのパラメーター値を取得できず、パーツはバイナリ入力ストリームを取得します
- パラメーターは、ファイル タイプ以外のパラメーター値のみを取得できます
- ファイルを取得するために Part を使用すると非常に便利です。ファイルのサイズとファイルの種類を取得できます。
Ⅰ: ファイルのアップロード
①フォームデータ型アップロード
form-data タイプは一般的に使用されるフォーム送信であり、フロント エンドからファイルを受信するには 2 つの方法があります
- 上記のパート、つまり @RequestPart アノテーションと request.getParts() を介してバイト ストリームを受信します。
- MultipartFile クラスを介してフロント エンドからファイルを受信する
説明: 2 つの方法は似ています
フロントエンド インターフェイスの送信
ファイルをアップロードするためのバックエンド コード (インターフェース)
/**
* form-data 类型(前端表单上传)
* @param request
* @param name
* @param file3
* @param photo
* @return
* @throws IOException
* @throws ServletException
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String readFile(HttpServletRequest request,
@RequestParam("name") String name,
@RequestPart("file1") MultipartFile file3,
@RequestPart("photo") MultipartFile photo
) throws IOException, ServletException {
System.out.println(name);
/*
第一种 : 使用 MultipartFile 封装好的 transferTo() 方法保存文件
photo.transferTo(new File(path + photo.getOriginalFilename()));
*/
/*
第二种 : 使用 MultipartFile 字节流保存文件
fileUtil(file3, String.valueOf(path));
*/
/*第三种 :用 Part 接收文件字节流
Part file2 = request.getPart("file2");
file2.write(path + file2.getSubmittedFileName());
request.getParts() 获取的是全部参数(name,age,file1,file2),包括文件参数和非文件参数
*/
for (Part part : request.getParts()) {
// 获取文件类型
part.getContentType();
// 获取文件大小
part.getSize();
// 获取文件名
part.getSubmittedFileName();
// 获取参数名 (name,age,file1,file2)
part.getName();
if(part.getContentType()!=null){
part.write(path + part.getSubmittedFileName());
}else{
// 可以获取文本参数值,文本参数 part.getContentType()为 null
System.out.println(request.getParameter(part.getName()));
}
}
return "success";
}
/**
* 字节流上传文件工具方法
* @param file
* @param path
* @return
*/
public String fileUtil(MultipartFile file, String path) {
if (!file.isEmpty()) {
try {
// 转化成字节流
byte[] bytes = file.getBytes();
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(
new File(path + file.getOriginalFilename())));
// 写出
bufferedOutputStream.write(bytes);
// 关闭资源
bufferedOutputStream.close();
return file.getOriginalFilename() + " 上传成功";
} catch (Exception e) {
return file.getOriginalFilename() + " failed to upload ---> " + e;
}
} else {
return file.getOriginalFilename() + "You failed to upload file was empty.";
}
}
テスト
②バイナリ型アップロード
バイナリ このタイプは、特定のバイナリ ファイルの MIME タイプを指定する、application/pdf などの一部のバイナリ ファイル タイプを指します。特定のサブタイプがない場合はテキスト ファイル タイプと同様
(サブタイプ)、text/plain を使用します。同様に、バイナリ ファイルには特定のサブタイプや既知のサブタイプはありません。つまり、アプリケーション ファイルのデフォルトである application/octet-stream を使用します。
アプリケーション/オクテット ストリームの場合、バイナリのみを送信でき、バイナリは 1 つだけ送信できます。ストリーム
(またはバイト配列)
フロントエンド インターフェイスの送信
ファイルをアップロードするためのバックエンド コード (インターフェース)
/**
* binary 类型上传
* @param request
* @return
* @throws IOException
*/
@RequestMapping(value = "/upload2",method = RequestMethod.POST)
public String upload2(HttpServletRequest request) throws IOException {
ServletInputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
// 获取上传的文件流
inputStream = request.getInputStream();
// 定义输出流 上传到哪里
fileOutputStream = new FileOutputStream(new File(path + "a.pdf"));
int len;
byte[] bytes = new byte[1024];
while((len = inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
} finally {
// 关闭资源
if(fileOutputStream!=null){
fileOutputStream.close();
}
if(inputStream!=null){
inputStream.close();
}
}
return "上传成功";
}
テスト
説明: part はより使いやすく、バイト ストリームを受け入れ、ファイル タイプ、ファイル名、ファイル サイズの読み取りがより便利です。
③設定手順
構成をカスタマイズしない場合、彼はデフォルト サイズの 1M\ をアップロードします。
SpringBoot プロジェクトは、構成ファイルを介して構成されます
server:
port: 8888
spring:
servlet:
multipart:
max-file-size: 10MB # 最大上传大小
max-request-size: 100MB # 单文件最大上传大小
Ⅱ:ファイルダウンロード
①補足説明
Content-Disposition
- 通常の HTTP 応答では、
Content-Disposition
応答ヘッダーは、応答のコンテンツを表示する形式、インライン(つまり、Web ページまたはページの一部) であるか、添付ファイルとしてローカルにダウンロードおよび保存されているかを示します。 - multipart/form-data タイプの応答メッセージ本文では、
Content-Disposition
メッセージ ヘッダーをマルチパート メッセージ本文のサブパートで使用して、対応するフィールドの関連情報を提供できます。Content-Type
各サブセクションは、で定義された区切り文字で区切られます。メッセージ本文自体で使用した場合、実際的な意味はありません。
文法:
-
メッセージ本文のメッセージ ヘッダーとして: HTTP シナリオでは、最初のパラメーターは
inline
(既定値。応答のメッセージ本文がページの一部またはページ全体として表示されることを示します)、またはattachment
(メッセージ本文はローカルにダウンロードする必要があります。ほとんどのブラウザでは、「名前を付けて保存」ダイアログが表示され、ダウンロードしたファイル名が存在する場合はその値が事前filename
に入力されます)。Content-Disposition: inline Content-Disposition: attachment Content-Disposition: attachment; filename="filename.jpg"
-
マルチパートボディのヘッダーとして: HTTP シナリオで。最初のパラメータは常に固定です
form-data
。追加のパラメータは大文字と小文字を区別せず、パラメータ値を持ちます。パラメータ名とパラメータ値は'='
等号 ( ) で接続され、パラメータ値は二重引用符で囲まれます。パラメータはセミコロン (';'
) で区切られます。Content-Disposition: form-data Content-Disposition: form-data; name="fieldName" Content-Disposition: form-data; name="fieldName"; filename="filename.jpg"
String パラメータと対応する response.setContentType() の型
ファイル拡張子 | Content-Type(Mime タイプ) | ファイル拡張子 | Content-Type(Mime タイプ) |
---|---|---|---|
.* (バイナリ ストリーム、ダウンロード ファイルの種類を認識しない) | アプリケーション/オクテット ストリーム | .tif | 画像/ティフ |
.001 | アプリケーション/x-001 | .301 | アプリケーション/x-301 |
.323 | テキスト/h323 | .906 | アプリケーション/x-906 |
.907 | ドローイング/907 | .a11 | アプリケーション/x-a11 |
.acp | audio/x-mei-aac | .ai | 申込書・追記 |
.aif | オーディオ/アイフ | .aifc | オーディオ/アイフ |
.aiff | オーディオ/アイフ | .anv | アプリケーション/x-anv |
。として | テキスト/そう | .asf | ビデオ/x-ms-asf |
.asp | テキスト/ASP | .asx | ビデオ/x-ms-asf |
.au | オーディオ/ベーシック | .avi | 私が見た |
.awf | アプリケーション/vnd.adobe.workflow | .biz | テキスト/xml |
.bmp | アプリケーション/x-bmp | .bot | アプリケーション/x-bot |
.c4t | アプリケーション/x-c4t | .c90 | アプリケーション/x-c90 |
.cal | アプリケーション/x-cals | 。猫 | アプリケーション/vnd.ms-pki.seccat |
.cdf | アプリケーション/x-netcdf | .cdr | アプリケーション/x-cdr |
.The | アプリケーション/エクセル | .cer | アプリケーション/x-x509-ca-cert |
.cg4 | アプリケーション/x-g4 | .cgm | アプリケーション/x-cgm |
.cit | アプリケーション/x-cit | 。クラス | ジャバ/* |
.cml | テキスト/xml | .cmp | アプリケーション/x-cmp |
.cmx | アプリケーション/x-cmx | .cot | アプリケーション/x-cot |
.crl | アプリケーション/pkix-crl | .crt | アプリケーション/x-x509-ca-cert |
.csi | アプリケーション/x-csi | .css | テキスト/CSS |
。切る | アプリケーション/X-カット | .dbf | アプリケーション/x-dbf |
.dbm | アプリケーション/x-dbm | .dbx | アプリケーション/x-dbx |
.dcd | テキスト/xml | .dcx | アプリケーション/x-dcx |
.the | アプリケーション/x-x509-ca-cert | 。と | アプリケーション/x-dgn |
。戻る | アプリケーション/x-ディブ | .dll | アプリケーション/x-msdownload |
.doc | アプリケーション/MSWORD | 。ドット | アプリケーション/MSWORD |
。終えた | アプリケーション/x-drw | .dtd | テキスト/xml |
。成長 | モデル/vnd.growth | 。成長 | アプリケーション/x-dwf |
.dwg | application/x-dwg | .dxb | application/x-dxb |
.dxf | application/x-dxf | .edn | application/vnd.adobe.edn |
.emf | application/x-emf | .eml | message/rfc822 |
.ent | text/xml | .epi | application/x-epi |
.eps | application/x-ps | .eps | application/postscript |
.etd | application/x-ebx | .exe | application/x-msdownload |
.fax | image/fax | .fdf | application/vnd.fdf |
.fif | application/fractals | .fo | text/xml |
.frm | application/x-frm | .g4 | application/x-g4 |
.gbr | application/x-gbr | . | application/x- |
.gif | image/gif | .gl2 | application/x-gl2 |
.gp4 | application/x-gp4 | .hgl | application/x-hgl |
.hmr | application/x-hmr | .hpg | application/x-hpgl |
.hpl | application/x-hpl | .hqx | application/mac-binhex40 |
.hrf | application/x-hrf | .hta | application/hta |
.htc | text/x-component | .htm | text/html |
.html | text/html | .htt | text/webviewhtml |
.htx | text/html | .icb | application/x-icb |
.ico | image/x-icon | .ico | application/x-ico |
.iff | application/x-iff | .ig4 | application/x-g4 |
.igs | application/x-igs | .iii | application/x-iphone |
.img | application/x-img | .ins | application/x-internet-signup |
.isp | application/x-internet-signup | .IVF | video/x-ivf |
.java | java/* | .jfif | image/jpeg |
.jpe | image/jpeg | .jpe | application/x-jpe |
.jpeg | image/jpeg | .jpg | image/jpeg |
.jpg | application/x-jpg | .js | application/x-javascript |
.jsp | text/html | .la1 | audio/x-liquid-file |
.lar | application/x-laplayer-reg | .latex | application/x-latex |
.lavs | audio/x-liquid-secure | .lbm | application/x-lbm |
.lmsff | audio/x-la-lms | .ls | application/x-javascript |
.ltr | application/x-ltr | .m1v | video/x-mpeg |
.m2v | video/x-mpeg | .m3u | audio/mpegurl |
.m4e | video/mpeg4 | .mac | application/x-mac |
.man | application/x-troff-man | .math | text/xml |
.mdb | application/msaccess | .mdb | application/x-mdb |
.mfp | application/x-shockwave-flash | .mht | message/rfc822 |
.mhtml | message/rfc822 | .mi | application/x-mi |
.mid | audio/mid | .midi | audio/mid |
.mil | application/x-mil | .mml | text/xml |
.mnd | audio/x-musicnet-download | .mns | audio/x-musicnet-stream |
.mocha | application/x-javascript | .movie | video/x-sgi-movie |
.mp1 | audio/mp1 | .mp2 | audio/mp2 |
.mp2v | video/mpeg | .mp3 | audio/mp3 |
.mp4 | video/mpeg4 | .mpa | video/x-mpg |
.mpd | application/vnd.ms-project | .mpe | video/x-mpeg |
.mpeg | video/mpg | .mpg | video/mpg |
.mpga | audio/rn-mpeg | .mpp | application/vnd.ms-project |
.mps | video/x-mpeg | .mpt | application/vnd.ms-project |
.mpv | video/mpg | .mpv2 | video/mpeg |
.mpw | application/vnd.ms-project | .mpx | application/vnd.ms-project |
.mtx | text/xml | .mxp | application/x-mmxp |
.net | image/pnetvue | .nrf | application/x-nrf |
.nws | message/rfc822 | .odc | text/x-ms-odc |
.out | application/x-out | .p10 | application/pkcs10 |
.p12 | application/x-pkcs12 | .p7b | application/x-pkcs7-certificates |
.p7c | application/pkcs7-mime | .p7m | application/pkcs7-mime |
.p7r | application/x-pkcs7-certreqresp | .p7s | application/pkcs7-signature |
.pc5 | application/x-pc5 | .pci | application/x-pci |
.pcl | application/x-pcl | .pcx | application/x-pcx |
application/pdf | application/pdf | ||
.pdx | application/vnd.adobe.pdx | .pfx | application/x-pkcs12 |
.pgl | application/x-pgl | .pic | application/x-pic |
.pko | application/vnd.ms-pki.pko | .pl | application/x-perl |
.plg | text/html | .pls | audio/scpls |
.plt | application/x-plt | .png | image/png |
.png | application/x-png | .pot | application/vnd.ms-powerpoint |
.ppa | application/vnd.ms-powerpoint | .ppm | application/x-ppm |
.pps | application/vnd.ms-powerpoint | .ppt | application/vnd.ms-powerpoint |
.ppt | application/x-ppt | .pr | application/x-pr |
.prf | application/pics-rules | .prn | application/x-prn |
.prt | application/x-prt | .ps | application/x-ps |
.ps | application/postscript | .ptn | application/x-ptn |
.pwz | application/vnd.ms-powerpoint | .r3t | text/vnd.rn-realtext3d |
.ra | audio/vnd.rn-realaudio | .ram | audio/x-pn-realaudio |
.ras | application/x-ras | .rat | application/rat-file |
.rdf | text/xml | .rec | application/vnd.rn-recording |
.red | application/x-red | .rgb | application/x-rgb |
.rjs | application/vnd.rn-realsystem-rjs | .rjt | application/vnd.rn-realsystem-rjt |
.rlc | application/x-rlc | .rle | application/x-rle |
.rm | application/vnd.rn-realmedia | .rmf | application/vnd.adobe.rmf |
.rmi | audio/mid | .rmj | application/vnd.rn-realsystem-rmj |
.rmm | audio/x-pn-realaudio | .rmp | application/vnd.rn-rn_music_package |
.rms | application/vnd.rn-realmedia-secure | .rmvb | application/vnd.rn-realmedia-vbr |
.rmx | application/vnd.rn-realsystem-rmx | .rnx | application/vnd.rn-realplayer |
.rp | image/vnd.rn-realpix | .rpm | audio/x-pn-realaudio-plugin |
.rsml | application/vnd.rn-rsml | .rt | text/vnd.rn-realtext |
.rtf | application/msword | .rtf | application/x-rtf |
.rv | video/vnd.rn-realvideo | .sam | application/x-sam |
.sat | application/x-sat | .sdp | application/sdp |
.sdw | application/x-sdw | .sit | application/x-stuffit |
.slb | application/x-slb | .sld | application/x-sld |
.slk | drawing/x-slk | .smi | application/smil |
.smil | application/smil | .smk | application/x-smk |
.snd | audio/basic | .sol | text/plain |
.sor | text/plain | .spc | application/x-pkcs7-certificates |
.spl | application/futuresplash | .spp | text/xml |
.ssm | application/streamingmedia | .sst | application/vnd.ms-pki.certstore |
.stl | application/vnd.ms-pki.stl | .stm | text/html |
.sty | application/x-sty | .svg | text/xml |
.swf | application/x-shockwave-flash | .tdf | application/x-tdf |
.tg4 | application/x-tg4 | .tga | application/x-tga |
.tif | image/tiff | .tif | application/x-tif |
.tiff | image/tiff | .tld | text/xml |
.top | drawing/x-top | .torrent | application/x-bittorrent |
.tsd | text/xml | .txt | text/plain |
.uin | application/x-icq | .uls | text/iuls |
.vcf | text/x-vcard | .vda | application/x-vda |
.vdx | application/vnd.visio | .vml | text/xml |
.vpg | application/x-vpeg005 | .vsd | application/vnd.visio |
.vsd | application/x-vsd | .vss | application/vnd.visio |
.vst | application/vnd.visio | .vst | application/x-vst |
.vsw | application/vnd.visio | .vsx | application/vnd.visio |
.vtx | application/vnd.visio | .vxml | text/xml |
.wav | audio/wav | .wax | audio/x-ms-wax |
.wb1 | application/x-wb1 | .wb2 | application/x-wb2 |
.wb3 | application/x-wb3 | .wbmp | image/vnd.wap.wbmp |
.wiz | application/msword | .wk3 | application/x-wk3 |
.wk4 | application/x-wk4 | .wkq | application/x-wkq |
.wks | application/x-wks | .wm | video/x-ms-wm |
.wma | audio/x-ms-wma | .wmd | application/x-ms-wmd |
.wmf | application/x-wmf | .wml | text/vnd.wap.wml |
.wmv | video/x-ms-wmv | .wmx | video/x-ms-wmx |
.wmz | application/x-ms-wmz | .wp6 | application/x-wp6 |
.wpd | application/x-wpd | .wpg | application/x-wpg |
.wpl | application/vnd.ms-wpl | .wq1 | application/x-wq1 |
.wr1 | application/x-wr1 | .wri | application/x-wri |
.wrk | application/x-wrk | .ws | application/x-ws |
.ws2 | application/x-ws | .wsc | text/scriptlet |
.wsdl | text/xml | .wvx | video/x-ms-wvx |
.xdp | application/vnd.adobe.xdp | .xdr | text/xml |
.xfd | application/vnd.adobe.xfd | .xfdf | application/vnd.adobe.xfdf |
.xhtml | text/html | .xls | application/vnd.ms-excel |
.xls | application/x-xls | .xlw | application/x-xlw |
.xml | text/xml | .xpl | audio/scpls |
.xq | text/xml | .xql | text/xml |
.xquery | text/xml | .xsd | text/xml |
.xsl | text/xml | .xslt | text/xml |
.xwd | application/x-xwd | .x_b | application/x-x_b |
.sis | application/vnd.symbian.install | .sisx | application/vnd.symbian.install |
.x_t | application/x-x_t | .ipa | application/vnd.iphone |
.apk | application/vnd.android.package-archive | .xap | アプリケーション/x-silverlight-アプリ |
② ローカルリソースをダウンロード
ダウンロードコード
/**
* 下载本地资源
* @param fileName 下载的文件名
* @param response 响应头
* @param isOnLine 是否默认下载 true浏览器中打开
* @throws IOException
*/
@GetMapping("/download")
public void download(String fileName, HttpServletResponse response, boolean isOnLine) throws IOException {
// 路径可以指定当前项目相对路径
File file = new File(path + fileName);
if (file.exists()) {
// 把文件转化成流
FileInputStream fileInputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
// 是否立即下载
if(!isOnLine){
response.setContentType("application/octet-stream");
// 如果文件名为中文需要设置编码
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("背景.jpg", "utf8"));
}
byte[] bytes = new byte[1024];
int len;
// 把文件流写入响应头
while ((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
}
}
リンクのテスト: http://localhost:8888/download?fileName=background.jpg
または http://localhost:8888/download?isOnLine=true&fileName=background.jpg
③ ネットワークリソースのダウンロード
コードのデモ
説明:目的のリソースを取得するには、最初に正しい URL を取得する必要があります
/**
* 下载网络资源
* @param response
* @throws IOException
*/
@RequestMapping("/downLoadMusic")
public void downloadNetworkFile(HttpServletResponse response) throws IOException {
// 创建url对象
URL url = new URL("https://m701.music.126.net/20221009103058/70acd1fa2256e82ae0a90f833aec1072/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/18195365565/53a1/ad15/9e1c/1b3457995065a152f56f61c38eda1914.m4a");
// 建立连接
URLConnection urlConnection = url.openConnection();
// 获取到输入流
InputStream inputStream = urlConnection.getInputStream();
// 获取到响应头的输出流
ServletOutputStream outputStream = response.getOutputStream();
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode("爱似水仙.m4a", "utf8"));
int len;
// 通过字节流下载下来
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1){
outputStream.write(bytes,0, len);
}
// 关闭资源
inputStream.close();
outputStream.close();
}
リンクのテスト: http://localhost:8888/downLoadMusic