首页>代码>Spring MVC+ajax+base64+amazeui框架上传头像带裁剪功能>/ImgUpload/src/com/lzh/controller/AjaxUpload.java
package com.lzh.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/upload")
public class AjaxUpload {
	@RequestMapping("/img")
	@ResponseBody
	public String uploadImg(@RequestParam("image") String imgStr, HttpSession session) {

		String filePath = null;
			String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
			
			filePath = session.getServletContext().getRealPath("/upload");
			//不存在就创建
			File file = new File(filePath);
			if (!file.exists() && !file.isDirectory()) {
				System.out.println("文件夹不存在");
				file.mkdir();
			}
			
			filePath = filePath + "\\" + uuid + ".jpg";
			try {
			//俩种方式解密Base64 后者更简单
		/*	// Base64
			byte[] b;
				b = decoder.decodeBuffer(imgStr.split(",")[1]);

				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {
						b[i] += 256;
					}
				}
				*/
				//因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
	            byte[] b = Base64Utils.decodeFromString(imgStr.split(",")[1]);
				System.out.println(filePath);
				OutputStream out = new FileOutputStream(filePath);
				out.write(b);
				out.flush();
				out.close();
			} catch (Exception e) {
				String json = "{\"result\":\"服务器异常\"}";
				return json;
			}
		String imgePath = "upload/" + uuid + ".jpg";
		String json = "{\"result\":\"ok\",\"file\":\""+imgePath+"\"}";
		System.out.println(json);
		return json;
	}
}
最近下载更多
fantesy  LV17 2021年4月7日
zhanss  LV7 2020年5月15日
pzy12345  LV8 2020年3月30日
我是谁0java  LV11 2019年6月11日
哇哩mxa  LV2 2019年6月1日
仪万里  LV12 2019年5月9日
peppa pig  LV1 2019年4月18日
2399431755  LV12 2019年4月3日
bailihui  LV4 2019年2月20日
skipple3  LV39 2019年2月13日
最近浏览更多
tianli3000  LV7 2022年2月24日
czr2233  LV9 2021年9月14日
1964867825 2021年9月6日
暂无贡献等级
天天  LV7 2021年9月4日
xiaoxiexie  LV13 2021年4月26日
fantesy  LV17 2021年4月7日
stellafull  LV2 2021年1月17日
helloworldsbsb  LV7 2020年12月28日
mengxiaoyao  LV3 2020年8月4日
dl51918  LV3 2020年6月23日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友