網上有很多上傳文件的教程,使用很不舒服,所以寫了這讀取上傳流文件的方法,方法輸出為String類型
/**
* 讀取流文件
* @return
* @throws IOException
*/
public static String getFIle() throws IOException {
// 讀取流文件
FileInputStream fis = new FileInputStream("F:\\test.txt");
// 防止路徑亂碼 如果utf-8 亂碼 改GBK eclipse里創建的txt 用UTF-8,在電腦上自己創建的txt 用GBK
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
// 設置一個接收的String
StringBuffer strBuf = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
strBuf.append(line);
}
String str= strBuf.toString();
br.close();
isr.close();
fis.close();
return str;
}
圖片上傳功能方法
/**
* 文件上傳功能
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadImg(HttpServletRequest request, HttpServletResponse response, MultipartFile file)
throws ServletException, IOException {
// 文件名字
System.out.println(file.getOriginalFilename());
InputStream files = file.getInputStream();
FileOutputStream out = new FileOutputStream(new File("E:\\" + file.getOriginalFilename() + ".jpeg"));
// 每次讀取的字節長度
int n = 0;
// 存儲每次讀取的內容
byte[] bb = new byte[1024];
while ((n = files.read(bb)) != -1) {
// 將讀取的內容,寫入到輸出流當中
out.write(bb, 0, n);
}
// 關閉輸入輸出流
out.close();
files.close();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
// 處理中文問題
sfu.setHeaderEncoding("UTF-8");
// 限制文件大小
sfu.setSizeMax(1024 * 1024 * 5);
// 輸出后路徑
String path = "";
// 把文件寫到指定路徑
path = "E:/" + File.separator;
// 打印文件位置
System.out.println(path);
}