java后台圖片的上傳預覽接口 IO流


上傳圖片接口    圖片保存到服務器(適用於任何文件)

/**
* 上傳醫生照片
* @param request
* @return
* @throws Exception
* @throws IOException
*/
@RequestMapping(value = "uploadfile")
public Object uploadfile(HttpServletRequest request) throws Exception, IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
String logoPathDir = fileConfig.getPersonImageURL(); //從配置文件中獲取服務器保存路徑
// 根據真實路徑創建目錄
File logoSaveFile = new File(logoPathDir);
if (!logoSaveFile.exists()){
logoSaveFile.mkdirs();
}
// 頁面控件的文件流
MultipartFile multipartFile = multipartRequest.getFile("file");
// 獲取文件的后綴
String suffix = multipartFile.getOriginalFilename().substring(
multipartFile.getOriginalFilename().lastIndexOf("."));
// 使用UUID生成文件名稱
String logImageName = UUID.randomUUID().toString() + suffix;// 構建文件名稱
// 拼成完整的文件保存路徑加文件
String fileName = logoPathDir + logImageName;
File file = new File(fileName);
try {
multipartFile.transferTo(file);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 打印出上傳到服務器的文件的絕對路徑
Map<String, Object> result=new HashMap<String, Object>();
result.put("imgname", logImageName);
result.put("imgnamepath", fileName);
result.put("message", "上傳成功");
result.put("statu", 1);
return result;
}

第二種寫法  io流
/**
* 上傳版本文件
* @param request
* @param response
* @return
* @throws Exception
* @throws IOException
*/
@RequestMapping(value = "uploadfiledemo")
public Object uploadfiledemo(HttpServletRequest request,MultipartHttpServletRequest multiReq,HttpServletResponse response) throws Exception, IOException {
// 獲取上傳文件的路徑
String uploadFilePath = multiReq.getFile("file").getOriginalFilename();
// 截取上傳文件的后綴
String uploadFileSuffix = uploadFilePath.substring(
uploadFilePath.lastIndexOf("."));
// 使用UUID生成文件名稱
String filename = UUID.randomUUID().toString() + uploadFileSuffix;// 構建文件名稱
FileOutputStream fos = null;
FileInputStream fis = null;
try {
fis = (FileInputStream) multiReq.getFile("file").getInputStream();
fos = new FileOutputStream(new File(fileConfig.getAppFileURL() + filename));
byte[] temp = new byte[1024];
int i = fis.read(temp);
while (i != -1) {
fos.write(temp, 0, temp.length);
fos.flush();
i = fis.read(temp);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 打印出上傳到服務器的文件的絕對路徑
Map<String, Object> result=new HashMap<String, Object>();
result.put("appFileName", filename);//文件名稱
result.put("appFilePath", fileConfig.getAppFileURL() + filename);//文件帶路徑的名稱
result.put("message", "上傳成功");
result.put("statu", 1);
return result;
}

------------------------------------------------------------------------------------------------------------------------------------------
圖片預覽接口 不需return 將文件流輸出即可
/**
* 傳入要預覽的圖片名稱
*
* @param path
*/
@RequestMapping(value = "/downloadpicture")
private void downloadPicture(String path, HttpServletResponse response) throws IOException {
//獲取文件保存路徑
String logoPathDir = fileConfig.getPersonImageURL();
path = logoPathDir + path; //獲取服務器上指定的圖片路徑
InputStream in = null;
ServletOutputStream sos = null;
try {
File file = new File(path);
in = new FileInputStream(file);
sos = response.getOutputStream();
byte[] b = new byte[1024];
while (in.read(b) != -1) {
sos.write(b); //輸出
}
sos.flush(); //刷新
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close(); //關閉文件讀取流,輸出流
sos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}



---------------------------------------------------------------------------------------------------------------------------------------

文件下載 保存到本地 需要設置文件頭,后綴名等信息 無法使用 文件需要使用FileInputStream

/**
* 傳入要下載的app文件的url,將url所對應的文件下載到本地
*
* @param path
*/
@RequestMapping(value = "/downloadappfile")
private void downloadappfile(@RequestParam(value="appFileName",defaultValue="")String path,HttpServletResponse response) throws IOException {
//獲取文件保存路徑
String logoPathDir = fileConfig.getAppFileURL();
path = logoPathDir + path;
InputStream in = null;
ServletOutputStream sos = null;
try {
File file = new File(path);
response.setCharacterEncoding("utf-8");
//設置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+file.getName());
//設置文件MIME類型
response.setContentType(new MimetypesFileTypeMap().getContentType(file));

in = new FileInputStream(file);
sos = response.getOutputStream();
byte[] b = new byte[1024];
while (in.read(b) != -1) {
sos.write(b);
}
sos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
sos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

 

 

 

第二種寫法  使用BufferedInputStream改善讀取性能

 /**
* 傳入要下載的app文件的url,將url所對應的文件下載到本地
* @param path
*/
@RequestMapping(value = "/downloadappfiledemo")
private void downloadappfiledemo(@RequestParam(value="appFileName",defaultValue="")String path,HttpServletResponse response) throws IOException {
//獲取文件保存路徑
String logoPathDir = fileConfig.getAppFileURL();
path = logoPathDir + path;
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
File file = new File(path);
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

InputStream不可以讀取文件,它是一個Abstract的類,根本不可能實例化,是所有輸入流的基類。而FileInputStream是InputStream的一個實現類,用於讀取諸如圖像數據之類的原始字節流。
第三種寫法
write的flush,是想要不關閉write流的情況下,將已寫入緩存的內容發出去。read只是讀操作,沒有flush。
out不關,是因為out來自socket,socket關了,就不用再關一次out了
/**
* 傳入要下載的app文件的url,將url所對應的文件下載到本地
* @param path
*/
@RequestMapping(value = "/downloadappfile")
private Object downloadappfile(@RequestParam(value="appFileName",defaultValue="")String path,HttpServletResponse response) throws IOException {
//獲取文件保存路徑
String logoPathDir = fileConfig.getAppFileURL();
path = logoPathDir + path;
File file = new File(path);
//如果文件不存在
if(!file.exists()){
return new Response("999999","系統找不到指定文件");
}
response.reset(); // 必要地清除response中的緩存信息
response.setContentType("application/octet-stream; charset=utf-8");
response.setCharacterEncoding("utf-8");
// 設置response的Header
response.setHeader("Content-Disposition", "attachment;filename="+file.getName());
response.addHeader("Content-Length", "" + file.length()); //設置請求頭信息寫入文件大小
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
bis = new BufferedInputStream(fis);
OutputStream os=response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
 
        
------------------------------------------------------------------------------------------------------------------

多文件上傳

public static String upload(HttpServletRequest request, String DirectoryName) throws IllegalStateException,
IOException {
// 創建一個通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
.getServletContext());
// 圖片名稱
String fileName = null;
// 判斷 request 是否有文件上傳,即多部分請求
if (multipartResolver.isMultipart(request)) {
// 轉換成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 記錄上傳過程起始時的時間,用來計算上傳時間
// int pre = (int) System.currentTimeMillis();
// 取得上傳文件
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 取得當前上傳文件的文件名稱
String myFileName = file.getOriginalFilename();
// 如果名稱不為“”,說明該文件存在,否則說明該文件不存在
if (myFileName.trim() != "") {
// 獲得圖片的原始名稱
String originalFilename = file.getOriginalFilename();
// 獲得圖片后綴名稱,如果后綴不為圖片格式,則不上傳
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
if (!fileTypes.contains(suffix)) {
continue;
}
// 獲得上傳路徑的絕對路徑地址(/upload)-->
String realPath = request.getSession().getServletContext().getRealPath("/" + DirectoryName);
System.out.println(realPath);
// 如果路徑不存在,則創建該路徑
File realPathDirectory = new File(realPath);
if (realPathDirectory == null || !realPathDirectory.exists()) {
realPathDirectory.mkdirs();
}
// 重命名上傳后的文件名 111112323.jpg
fileName = UUID.randomUUID().toString() + suffix;// 構建文件名稱
// 定義上傳路徑 .../upload/111112323.jpg
File uploadFile = new File(realPathDirectory + "\\" + fileName);
System.out.println(uploadFile);
file.transferTo(uploadFile);
}
}
// 記錄上傳該文件后的時間
// int finaltime = (int) System.currentTimeMillis();
// System.out.println(finaltime - pre);
}
}
return fileName;
}

------------------------------------------------------------------------------------------------------------------------------------------
Java IO 的一般使用原則 :  
一、按數據來源(去向)分類:
1 、是文件: FileInputStream, FileOutputStream, ( 字節流 )FileReader, FileWriter( 字符 )
2 、是 byte[] : ByteArrayInputStream, ByteArrayOutputStream( 字節流 )
3 、是 Char[]: CharArrayReader, CharArrayWriter( 字符流 )
4 、是 String: StringBufferInputStream, StringBufferOuputStream ( 字節流 )StringReader, StringWriter( 字符流 )
5 、網絡數據流: InputStream, OutputStream,( 字節流 ) Reader, Writer( 字符流 )
二、按是否格式化輸出分:
1 、要格式化輸出: PrintStream, PrintWriter
三、按是否要緩沖分:
1 、要緩沖: BufferedInputStream, BufferedOutputStream,( 字節流 ) BufferedReader, BufferedWriter( 字符流 )
四、按數據格式分:
1 、二進制格式(只要不能確定是純文本的) : InputStream, OutputStream 及其所有帶 Stream 結束的子類
2 、純文本格式(含純英文與漢字或其他編碼方式); Reader, Writer 及其所有帶 Reader, Writer 的子類
五、按輸入輸出分:
1 、輸入: Reader, InputStream 類型的子類
2 、輸出: Writer, OutputStream 類型的子類
六、特殊需要:
1 、從 Stream 到 Reader,Writer 的轉換類: InputStreamReader, OutputStreamWriter
2 、對象輸入輸出: ObjectInputStream, ObjectOutputStream
3 、進程間通信: PipeInputStream, PipeOutputStream, PipeReader, PipeWriter
4 、合並輸入: SequenceInputStream
5 、更特殊的需要: PushbackInputStream, PushbackReader, LineNumberInputStream, LineNumberReader
決定使用哪個類以及它的構造進程的一般准則如下(不考慮特殊需要):
首先,考慮最原始的數據格式是什么: 原則四
第二,是輸入還是輸出:原則五
第三,是否需要轉換流:原則六第 1 點
第四,數據來源(去向)是什么:原則一
第五,是否要緩沖:原則三 (特別注明:一定要注意的是 readLine() 是否有定義,有什么比 read, write 更特殊的輸入或輸出方法)
第六,是否要格式化輸出:原則二





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM