Java客戶(hù)端服務(wù)端上傳接收文件實(shí)現(xiàn)詳解
Java客戶(hù)端通過(guò)HTTP協(xié)議上傳文件, 服務(wù)端處理客戶(hù)端請(qǐng)求, MultipartFile轉(zhuǎn)File, 實(shí)現(xiàn)客戶(hù)端上傳文件的存儲(chǔ)
Java環(huán)境: JDK1.8開(kāi)發(fā)環(huán)境: IDEASpringBoot: 2.2.0Maven: 3.6.3
Java客戶(hù)端通過(guò)HTTP協(xié)議上傳文件
// 引入pom依賴(lài), hutool相關(guān)文檔, https://www.hutool.cn/docs/<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.7</version></dependency>
HashMap<String, Object> paramMap = new HashMap<>();//文件上傳只需將參數(shù)中的鍵指定(默認(rèn)file),值設(shè)為文件對(duì)象即可,對(duì)于使用者來(lái)說(shuō),文件上傳與普通表單提交并無(wú)區(qū)別paramMap.put('file', FileUtil.file('C:文件路徑文件名稱(chēng)'));String result = HttpUtil.post('服務(wù)端IP:端口', paramMap);
Java服務(wù)端接收請(qǐng)求并實(shí)現(xiàn)文件的存儲(chǔ)
工具類(lèi)
public class Utils { public static void saveFile( MultipartFile filecontent){ OutputStream os = null; InputStream inputStream = null; String fileName = null; try { inputStream = filecontent.getInputStream(); fileName = filecontent.getOriginalFilename(); } catch (IOException e) { e.printStackTrace(); } try { String path = 'C:test'; // 2、保存到臨時(shí)文件 // 1K的數(shù)據(jù)緩沖 byte[] bs = new byte[1024]; // 讀取到的數(shù)據(jù)長(zhǎng)度 int len; // 輸出的文件流保存到本地文件 File tempFile = new File(path); if (!tempFile.exists()) {tempFile.mkdirs(); } os = new FileOutputStream(tempFile.getPath() + File.separator + fileName); // 開(kāi)始讀取 while ((len = inputStream.read(bs)) != -1) {os.write(bs, 0, len); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 完畢,關(guān)閉所有鏈接 try {os.close();inputStream.close(); } catch (IOException e) {e.printStackTrace(); } } }}
Controller類(lèi)
@Controllerpublic class FileController { @RequestMapping('/') @ResponseBody public String index(@RequestParam(value = 'file', required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { Utils.saveFile(file); return 'Success'; }}
注意:
文件較大時(shí)spring-boot 服務(wù)端報(bào)上傳文件錯(cuò)誤“spring.servlet.multipart.max-file-size”
可以修改配置文件: application.properties, 添加以下配置..大小自行修改...
spring.servlet.multipart.max-file-size=200MBspring.servlet.multipart.max-request-size=200MB
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JS實(shí)現(xiàn)前端動(dòng)態(tài)分頁(yè)碼代碼實(shí)例2. 關(guān)于IDEA 2020.3 多窗口視圖丟失的問(wèn)題3. javascript實(shí)現(xiàn)貪吃蛇小練習(xí)4. js實(shí)現(xiàn)碰撞檢測(cè)5. 一文帶你徹底理解Java序列化和反序列化6. 用Spring JMS使異步消息變得簡(jiǎn)單7. PHP驗(yàn)證碼工具-Securimage8. Python 制作查詢(xún)商品歷史價(jià)格的小工具9. Python 利用Entrez庫(kù)篩選下載PubMed文獻(xiàn)摘要的示例10. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條

網(wǎng)公網(wǎng)安備