java實(shí)現(xiàn)文件保存到本地的方法
本篇介紹了java實(shí)現(xiàn)文件保存到本地的方法,具體代碼如下:
private void savePic(InputStream inputStream, String fileName) {
OutputStream os = null;
try {
String path = "D:\\testFile\\";
// 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();
}
}
}
文件保存方法.
附:
package com.ebways.web.upload.controller;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.ebways.web.base.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ebways.web.upload.url.UploadURL;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping(value = UploadURL.MODE_NAME)
public class UploadController extends BaseController {
@RequestMapping(value = UploadURL.IMAGE_UPLOAD)
@ResponseBody
public String uploadFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IllegalArgumentException, Exception {
// 參數(shù)列表
Map<String, Object> map = new HashMap<>();
map.put("file", file);
savePic(file.getInputStream(), file.getOriginalFilename());
//請(qǐng)求接口
String apiReturnStr = "";//apiHttpRequest(map, API_HOST_URL + "/image/upload");
return apiReturnStr;
}
private void savePic(InputStream inputStream, String fileName) {
OutputStream os = null;
try {
String path = "D:\\testFile\\";
// 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();
}
}
}
/**
* <p class="detail">
* 功能:公共Action
* </p>
*
* @date 2016年9月8日
* @author wangsheng
*/
private String allowSuffix = "jpg,png,gif,jpeg";//允許文件格式
private long allowSize = 2L;//允許文件大小
private String fileName;
private String[] fileNames;
public String getAllowSuffix() {
return allowSuffix;
}
public void setAllowSuffix(String allowSuffix) {
this.allowSuffix = allowSuffix;
}
public long getAllowSize() {
return allowSize * 1024 * 1024;
}
public void setAllowSize(long allowSize) {
this.allowSize = allowSize;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String[] getFileNames() {
return fileNames;
}
public void setFileNames(String[] fileNames) {
this.fileNames = fileNames;
}
/**
* <p class="detail">
* 功能:重新命名文件
* </p>
*
* @return
* @author wangsheng
* @date 2016年9月8日
*/
private String getFileNameNew() {
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return fmt.format(new Date());
}
/**
* <p class="detail">
* 功能:文件上傳
* </p>
*
* @param files
* @param destDir
* @throws Exception
* @author wangsheng
* @date 2014年9月25日
*/
public void uploads(MultipartFile[] files, String destDir, HttpServletRequest request) throws Exception {
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
try {
fileNames = new String[files.length];
int index = 0;
for (MultipartFile file : files) {
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
int length = getAllowSuffix().indexOf(suffix);
if (length == -1) {
throw new Exception("請(qǐng)上傳允許格式的文件");
}
if (file.getSize() > getAllowSize()) {
throw new Exception("您上傳的文件大小已經(jīng)超出范圍");
}
String realPath = request.getSession().getServletContext().getRealPath("/");
File destFile = new File(realPath + destDir);
if (!destFile.exists()) {
destFile.mkdirs();
}
String fileNameNew = getFileNameNew() + "." + suffix;//
File f = new File(destFile.getAbsoluteFile() + "\\" + fileNameNew);
file.transferTo(f);
f.createNewFile();
fileNames[index++] = basePath + destDir + fileNameNew;
}
} catch (Exception e) {
throw e;
}
}
/**
*功能:文件上傳
*
* @param file
* @param destDir
* @throws Exception
* @author wangsheng
* @date 2016年9月8日
*/
public void upload(MultipartFile file, String destDir, HttpServletRequest request) throws Exception {
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
try {
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
int length = getAllowSuffix().indexOf(suffix);
if (length == -1) {
throw new Exception("請(qǐng)上傳允許格式的文件");
}
if (file.getSize() > getAllowSize()) {
throw new Exception("您上傳的文件大小已經(jīng)超出范圍");
}
String realPath = request.getSession().getServletContext().getRealPath("/");
File destFile = new File(realPath + destDir);
if (!destFile.exists()) {
destFile.mkdirs();
}
String fileNameNew = getFileNameNew() + "." + suffix;
File f = new File(destFile.getAbsoluteFile() + "/" + fileNameNew);
file.transferTo(f);
f.createNewFile();
fileName = basePath + destDir + fileNameNew;
} catch (Exception e) {
throw e;
}
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Lombok插件有望被Intellij IDEA收編以改善兼容性問(wèn)題(推薦)
這篇文章主要介紹了Lombok插件有望被Intellij IDEA收編以改善兼容性問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
SpringCloud Nacos集群搭建過(guò)程詳解
Nacos集群不僅僅是服務(wù)注冊(cè)中心,還在微服務(wù)架構(gòu)中發(fā)揮著關(guān)鍵的角色,支持多種場(chǎng)景下的服務(wù)治理和協(xié)調(diào),本文介紹了如何在SpringCloud環(huán)境中搭建Nacos集群,為讀者提供了一份清晰而詳盡的指南,通過(guò)逐步演示每個(gè)關(guān)鍵步驟,讀者能夠輕松理解并操作整個(gè)搭建過(guò)程2024-02-02
啟動(dòng)Tomcat報(bào)錯(cuò)Unsupported major.minor version xxx的解決方法
這篇文章主要為大家詳細(xì)介紹了啟動(dòng)Tomcat報(bào)錯(cuò)Unsupported major.minor version xxx的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
MyBatis一次執(zhí)行多條SQL語(yǔ)句的操作
這篇文章主要介紹了MyBatis一次執(zhí)行多條SQL語(yǔ)句的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12
Spring的事件監(jiān)聽(tīng)機(jī)制示例詳解
這篇文章主要給大家介紹了關(guān)于Spring的事件監(jiān)聽(tīng)機(jī)制的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
SpringBoot搭建多數(shù)據(jù)源的實(shí)現(xiàn)方法
說(shuō)起多數(shù)據(jù)源,一般都來(lái)解決那些問(wèn)題呢,主從模式或者業(yè)務(wù)比較復(fù)雜需要連接不同的分庫(kù)來(lái)支持業(yè)務(wù)。本文主要介紹了SpringBoot搭建多數(shù)據(jù)源的實(shí)現(xiàn)方法,感興趣的可以了解一下,感興趣的可以額了解一下2021-12-12
JAVA 線(xiàn)程通信相關(guān)知識(shí)匯總
這篇文章主要介紹了JAVA 線(xiàn)程通信相關(guān)知識(shí),文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06

