由于現(xiàn)在很多業(yè)務(wù)需要文件上傳僵缺,而且前端上傳的格式不同,有的是Base64格式踩叭,也可能是正常的圖片格式磕潮,所以就把這些整理出來(lái),方便以后用到容贝。也方便大家自脯。如果有什么不好之處,請(qǐng)大家麻煩給點(diǎn)意見(jiàn)斤富。謝謝8喑薄!
基于maven 創(chuàng)建的文件上傳满力。
所需要的 jar
commons-fileupload commons-fileupload 1.3.1
commons-httpclient commons-httpclient 3.1
net.coobird thumbnailator 0.4.8 //圖片壓縮所用
首先 方法要實(shí)現(xiàn)?ServletContextAware 類(lèi) 重寫(xiě)?ServletContext
public class FileController implements ServletContextAware{
????????private ServletContext servletContext;
????????@Override
????????public void setServletContext(ServletContext servletContext) {
????????????this.servletContext = servletContext;
????????}
}
下面是上傳正常圖片格式的代碼
@RequestMapping(value="fileUploadImg",method=RequestMethod.POST)
@ResponseBody
public JsonData fileUpload( @RequestParam("file") CommonsMultipartFile file){
????JsonData data = new JsonData();
????data.setResult(0);
????try {
? ?????????????????? //文件上傳保存的路徑
??????????????????String realPaths = Config.UPLOAD_BASE_DIR+"/"+DateUtil.stampToDate(System.currentTimeMillis(), "yyyy/MM/dd");
? ? ? ? ? ? ? ? ? ? String abspath = servletContext.getRealPath(realPath);//獲取絕對(duì)路徑
? ? ? ? ? ? ? ? ? ? ?File uploadDir = new File(abspath);
????????????????????if (!uploadDir.exists()) {
????????????????????????????uploadDir.mkdirs();
????????????????????}
????????????????????String fileName = randName() + file.getOriginalFilename();//設(shè)置文件名
????????????????????File tagelFile = new File(abspath, fileName);
????????????????????file.transferTo(tagelFile);
????????????????????System.out.println(tagelFile.getPath());
????????????????????data.setData(fileName); data.setResult(1);
????????????} catch (Exception e) {
????????????????e.printStackTrace();
????????????????data.setErrMsg("圖片服務(wù)器服務(wù)繁忙");
????????????}
????????????return data;
}
設(shè)置隨機(jī)的文件名 防止出現(xiàn)重名
/** * 隨機(jī) * * @return */
@SuppressWarnings("static-access")
private static String randName() {
????Calendar calendar = Calendar.getInstance();
????StringBuffer sb = new StringBuffer();
????sb.append(calendar.get(calendar.YEAR));
????sb.append(calendar.get(calendar.MONTH) + 1);
????sb.append(calendar.get(calendar.DATE));
????sb.append(calendar.get(calendar.HOUR));
????sb.append(calendar.get(calendar.MINUTE));
????sb.append(calendar.get(calendar.SECOND));
????Random random = new Random();
????Integer n = random.nextInt(999999);
????sb.append(n.toString());
????return sb.toString();
}
前端上傳的圖片格式為base64的上傳代碼如下
@RequestMapping(value="base64File",method=RequestMethod.POST)
@ResponseBody
public JsonData base64File(@RequestBody String file){
????????MyLogUtils.getInstance().log("開(kāi)始上傳圖片");
????????JsonData data = new JsonData();
????????data.setResult(1);
????????try {
????????????????file=file.replaceAll("\"", "");
????????????????String realPath = Config.UPLOAD_BASE_DIR+DateUtil.stampToDate(System.currentTimeMillis(), "yyyy/MM/dd");
????????????????String abspath = servletContext.getRealPath(realPath);
????????????????File uploadDir = new File(abspath);
????????????????if (!uploadDir.exists()) {
????????????????????????uploadDir.mkdirs();
? ? ? ? ? ? ? ? ? }
????????????????String fileName = randName()+".jpg";
????????????????Base64File.generateImage(file, abspath+"/"+fileName);
????????????????data.setData(fileName);
????????????????data.setResult(0);
????????????????MyLogUtils.getInstance().log("上傳圖片成功");
????????????} catch (Exception e) {
????????????????e.printStackTrace();
????????????????data.setErrMsg("圖片服務(wù)器服務(wù)繁忙");
????????} return data;
}
有時(shí)候咱們遇到用戶(hù)上傳的圖片很大焕参,那么我們就需要壓縮圖片并保留原圖,代碼如下
@RequestMapping(value="imgFileCompress",method=RequestMethod.POST)
@ResponseBody
public Json<Data> uploadFileAndCreateThumbnail(@RequestParam("file") CommonsMultipartFile imageFile) {
????Json<Data> data = new Json<Data>();
????data.setResult(0);
????if(imageFile == null ){
????????data.setErrMsg("imageFile不能為空");
????????return data;
????}
????if (imageFile.getSize() >= 10*1024*1024){
????????data.setErrMsg("文件不能大于10M");
????????return data;
????}
????//拼接后臺(tái)文件名稱(chēng)
????String pathName = randName() + "." + FilenameUtils.getExtension(imageFile.getOriginalFilename()); //文件存放路徑
????String realPaths = Config.UPLOAD_BASE_DIR+"/"+DateUtil.stampToDate(System.currentTimeMillis(), "yyyy/MM/dd"); //構(gòu)建保存文件路徑
????String realPath = servletContext.getRealPath(realPaths); //拼接文件路徑
????String filePathName = realPath + File.separator + pathName; System.out.println("圖片上傳路徑:"+filePathName);
????//判斷文件保存是否存在
????File file = new File(filePathName);
????if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
????????//創(chuàng)建文件 file.getParentFile().mkdirs();
????}
????InputStream inputStream = null;
????FileOutputStream fileOutputStream = null;
????try {
????????inputStream = imageFile.getInputStream();
????????fileOutputStream = new FileOutputStream(file);
????????//寫(xiě)出文件
????????byte[] buffer = new byte[2048];
????????IOUtils.copyLarge(inputStream, fileOutputStream, buffer);
????????buffer = null;
????} catch (IOException e) {
????????filePathName = null;
????????data.setErrMsg("操作失敗");
????????e.printStackTrace();
????????return data;
????} finally {
????????try {
????????????if (inputStream != null) {
????????????????inputStream.close();
????????????}
????????????if (fileOutputStream != null) {
????????????????fileOutputStream.flush();
????????????????fileOutputStream.close();
????????????}
????????} catch (IOException e) {
????????????filePathName = null;
????????????data.setErrMsg("操作失敗");
????????????return data;
????????}
????}
????/*** 縮略圖begin*/
????//拼接后臺(tái)文件名稱(chēng)
? ? String thumbnailPathName = randName() + "small." + FilenameUtils.getExtension(imageFile.getOriginalFilename()); ????if(thumbnailPathName.contains(".png")){
????????????thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
????}
????long size = imageFile.getSize();
????double scale = 1.0d ;
????if(size >= 200*1024){
????????if(size > 0){
????????????scale = (200*1024f) / size ;
????????}
????}
? ? //拼接文件路徑
? ? String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;
????try {
????????if(size < 200*1024){
????????????Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
????????}else{
????????????Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
????????}
????} catch (Exception e1) {
????????data.setErrMsg("操作失敗");
????????return data;
????}
????/*** 縮略圖end*/
????Map map = new HashMap();
????//原圖地址
????map.put("originalUrl", pathName);
????//縮略圖地址
????map.put("thumbnailUrl", thumbnailPathName);
????data.setData(map);
????data.setResult(1);
????return data;
}
附加:base64 與 圖片之間的互相轉(zhuǎn)換
1.圖片轉(zhuǎn)Base64
/** * @Description: 根據(jù)圖片地址轉(zhuǎn)換為base64編碼字符串
????* @Author: * @CreateTime: * @return */
public static String getImageStr(String imgFile) {
? ? InputStream inputStream = null;
????byte[] data = null;
try {
????inputStream = new FileInputStream(imgFile);
????data = new byte[inputStream.available()];
????inputStream.read(data);
????inputStream.close();
????} catch (IOException e) {
????e.printStackTrace();
????}
????// 加密
????BASE64Encoder encoder = new BASE64Encoder();
????return encoder.encode(data);
}
2.base64 轉(zhuǎn) 圖片
/** * @Description: 將base64編碼字符串轉(zhuǎn)換為圖片 * @Author: * @CreateTime:
* @param imgStr base64編碼字符串 * @param path 圖片路徑-具體到文件 * @return */
public static boolean generateImage(String imgStr, String path) {
????if (imgStr == null){
????return false;
????}
????BASE64Decoder decoder = new BASE64Decoder();
try {
????// 解密
????byte[] b = decoder.decodeBuffer(imgStr);
????????// 處理數(shù)據(jù)
????????for (int i = 0; i < b.length; ++i) {
????????????if (b[i] < 0) { b[i] += 256;
????????}
????}
????OutputStream out = new FileOutputStream(path);
????out.write(b);
????out.flush();
????out.close();
????return true;
????}catch(Exception ex){
????return false;
????}
}