日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

java后台图片的上传预览接口 IO流

發(fā)布時(shí)間:2025/6/15 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java后台图片的上传预览接口 IO流 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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

/**
* 上傳醫(yī)生照片
* @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(); //從配置文件中獲取服務(wù)器保存路徑
// 根據(jù)真實(shí)路徑創(chuàng)建目錄
File logoSaveFile = new File(logoPathDir);
if (!logoSaveFile.exists()){
logoSaveFile.mkdirs();
}
// 頁(yè)面控件的文件流
MultipartFile multipartFile = multipartRequest.getFile("file");
// 獲取文件的后綴
String suffix = multipartFile.getOriginalFilename().substring(
multipartFile.getOriginalFilename().lastIndexOf("."));
// 使用UUID生成文件名稱
String logImageName = UUID.randomUUID().toString() + suffix;// 構(gòu)建文件名稱
// 拼成完整的文件保存路徑加文件
String fileName = logoPathDir + logImageName;
File file = new File(fileName);
try {
multipartFile.transferTo(file);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 打印出上傳到服務(wù)器的文件的絕對(duì)路徑
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;// 構(gòu)建文件名稱
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();
}
}
}
// 打印出上傳到服務(wù)器的文件的絕對(duì)路徑
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;
}
------------------------------------------------------------------------------------------------------------------------------------------
圖片預(yù)覽接口 不需return 將文件流輸出即可 /**
* 傳入要預(yù)覽的圖片名稱
*
* @param path
*/
@RequestMapping(value = "/downloadpicture")
private void downloadPicture(String path, HttpServletResponse response) throws IOException {
//獲取文件保存路徑
String logoPathDir = fileConfig.getPersonImageURL();
path = logoPathDir + path; //獲取服務(wù)器上指定的圖片路徑
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(); //關(guān)閉文件讀取流,輸出流
sos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}



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

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

/**
* 傳入要下載的app文件的url,將url所對(duì)應(yīng)的文件下載到本地
*
* @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");
//設(shè)置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+file.getName());
//設(shè)置文件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所對(duì)應(yīng)的文件下載到本地
* @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不可以讀取文件,它是一個(gè)Abstract的類,根本不可能實(shí)例化,是所有輸入流的基類。而FileInputStream是InputStream的一個(gè)實(shí)現(xiàn)類,用于讀取諸如圖像數(shù)據(jù)之類的原始字節(jié)流。
第三種寫法
write的flush,是想要不關(guān)閉write流的情況下,將已寫入緩存的內(nèi)容發(fā)出去。read只是讀操作,沒有flush。
out不關(guān),是因?yàn)閛ut來(lái)自socket,socket關(guān)了,就不用再關(guān)一次out了
/**
* 傳入要下載的app文件的url,將url所對(duì)應(yīng)的文件下載到本地
* @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","系統(tǒng)找不到指定文件");
}
response.reset(); // 必要地清除response中的緩存信息
response.setContentType("application/octet-stream; charset=utf-8");
response.setCharacterEncoding("utf-8");
// 設(shè)置response的Header
response.setHeader("Content-Disposition", "attachment;filename="+file.getName());
response.addHeader("Content-Length", "" + file.length()); //設(shè)置請(qǐng)求頭信息寫入文件大小
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 {
// 創(chuàng)建一個(gè)通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
.getServletContext());
// 圖片名稱
String fileName = null;
// 判斷 request 是否有文件上傳,即多部分請(qǐng)求
if (multipartResolver.isMultipart(request)) {
// 轉(zhuǎn)換成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 記錄上傳過(guò)程起始時(shí)的時(shí)間,用來(lái)計(jì)算上傳時(shí)間
// int pre = (int) System.currentTimeMillis();
// 取得上傳文件
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 取得當(dāng)前上傳文件的文件名稱
String myFileName = file.getOriginalFilename();
// 如果名稱不為“”,說(shuō)明該文件存在,否則說(shuō)明該文件不存在
if (myFileName.trim() != "") {
// 獲得圖片的原始名稱
String originalFilename = file.getOriginalFilename();
// 獲得圖片后綴名稱,如果后綴不為圖片格式,則不上傳
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
if (!fileTypes.contains(suffix)) {
continue;
}
// 獲得上傳路徑的絕對(duì)路徑地址(/upload)-->
String realPath = request.getSession().getServletContext().getRealPath("/" + DirectoryName);
System.out.println(realPath);
// 如果路徑不存在,則創(chuàng)建該路徑
File realPathDirectory = new File(realPath);
if (realPathDirectory == null || !realPathDirectory.exists()) {
realPathDirectory.mkdirs();
}
// 重命名上傳后的文件名 111112323.jpg
fileName = UUID.randomUUID().toString() + suffix;// 構(gòu)建文件名稱
// 定義上傳路徑 .../upload/111112323.jpg
File uploadFile = new File(realPathDirectory + "\\" + fileName);
System.out.println(uploadFile);
file.transferTo(uploadFile);
}
}
// 記錄上傳該文件后的時(shí)間
// int finaltime = (int) System.currentTimeMillis();
// System.out.println(finaltime - pre);
}
}
return fileName;
}

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



轉(zhuǎn)載于:https://www.cnblogs.com/1234cjq/p/7649444.html

總結(jié)

以上是生活随笔為你收集整理的java后台图片的上传预览接口 IO流的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。