Java客戶端服務(wù)端上傳接收文件實(shí)現(xiàn)詳解
Java客戶端通過(guò)HTTP協(xié)議上傳文件, 服務(wù)端處理客戶端請(qǐng)求, MultipartFile轉(zhuǎn)File, 實(shí)現(xiàn)客戶端上傳文件的存儲(chǔ)
Java環(huán)境: JDK1.8開發(fā)環(huán)境: IDEASpringBoot: 2.2.0Maven: 3.6.3
Java客戶端通過(guò)HTTP協(xié)議上傳文件
// 引入pom依賴, 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:文件路徑文件名稱'));String result = HttpUtil.post('服務(wù)端IP:端口', paramMap);
Java服務(wù)端接收請(qǐng)求并實(shí)現(xiàn)文件的存儲(chǔ)
工具類
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); // 開始讀取 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類
@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. python裝飾器三種裝飾模式的簡(jiǎn)單分析2. 詳解java中static關(guān)鍵詞的作用3. Python如何進(jìn)行時(shí)間處理4. 詳解Python模塊化編程與裝飾器5. Java14發(fā)布了,再也不怕NullPointerException了6. PHP擴(kuò)展之字符編碼相關(guān)函數(shù)1——iconv7. python使用ctypes庫(kù)調(diào)用DLL動(dòng)態(tài)鏈接庫(kù)8. 關(guān)于Java下奇怪的Base64詳解9. Python實(shí)現(xiàn)迪杰斯特拉算法過(guò)程解析10. PHP swoole的process模塊創(chuàng)建和使用子進(jìn)程操作示例
