您的位置:首页 > 编程语言 > Java开发

详解js插件ajaxupload实现图片上传(适用springboot)

2018-01-06 10:35 951 查看
详解js插件ajaxupload实现图片上传
1、插件引用

<script src="../../js/common/ajaxupload.js"></script>2、html代码

这是bootstrap的弹出框,其中#show_img部分为上传图片的关键代码
<!--遮罩和弹窗/修改 begin-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" >修改热门推荐</h4>
</div>
<div class="modal-body">
<label for="recoSoft" class="text-right search_form_div_label">排序:</label>
<input type="text" class="form-control" id="recoSoft" maxlength="5" onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="请输入排序" style="width: 200px;"/>
<label  class="text-right search_form_div_label img_title">图片:</label>
<div class="show_img">
<img id="closeImg" style="display:none" alt="" src="../../images/message_delete.png">
<img id="uploadImg" alt="" src="../../images/addImg.png">
</div>
<!--确定和取消-->
<div class="btn_box">
<button type="button" id="saveRecommend" class="btn btn-success">保 存</button>
<button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
</div>
</div>
</div>
</div>
</div>
3、css代码
.show_img{
position: relative;
}
#closeImg{
width: 20px;
height: 20px;
position: absolute;
top: -20px;
right: 140px;
}
#uploadImg{
width: 300px;
height: 200px;
margin-left: 105px;
}
#recoSoft{
display: inline-block;
}
.img_title{
margin-top: 20px;
display: block;
}
.btn_box{
text-align: right;
}4、js关键代码

需要初始化引用如:
jQuery(document).ready(function() {
recommend.init(); \\recommend是自定义的js文件名
});
init: function() {
// 图片上传
recommend.uploadimg();
},

上传图片关键代码
/**
* 上传图片
* @returns
*/
uploadimg:function(){
var index;
var button = $('#uploadImg'); //点击触发事件
new AjaxUpload(button,{
action: '../../poi/poiRecommend/uploadImg.do', //接口路径
name: 'img',
onSubmit : function(file, ext){
if (ext && /^(jpg|JPG|jpeg|JPEG|png|PNG|gif|bmp)$/.test(ext)){
// 开启加载层
index = layer.load(2, {
shade: [0.1,'#fff'] //0.1透明度的白色背景
});
return true;
} else {
layer.msg('非图片类型文件,请重传!');
return false;
}
},
onComplete: function(file, result){ //上传完毕后的操作
layer.close(index); // 关闭加载层
var data = $.parseJSON(result.replace(/<.*?>/ig,"")); //解析带有<pre>的结果,如果无直接使用
if(data.resCode=="0"){
$("#uploadImg").attr("src",data.resData.fileUrl);
$("#closeImg").show();
}else{
layer.msg("上传失败");
}
}
});
}, 5、后台controller接口代码
@PostMapping("/uploadImg")
public String uploadImg(HttpSession session,@RequestParam("img") MultipartFile mFile) throws Exception{

log.info(GlobalContract.LOG_BEGIN);
ResultVO resultVO = null;

if (!mFile.isEmpty()) {

// 新文件名
String name = GlobalContract.APK_PREFIX.concat(FileOptionUtil.getfileName());
// 文件本地保存路径
String filePath = GlobalContract.FILEPATH_APP_VERSION;
// 存入文件服务器的路径
String url = GlobalContract.URL_IMG.concat(GlobalContract.POI_RECOMMEND_IMG);   //POI_RECOMMEND_IMG为自定义保存路径

// 保存文件到本地tomcat
Map<String, String> map = UploadFileUtil.uploadFile(mFile, name, filePath, url);
System.out.println(map);
// 保存文件到文件服务器
List<String> list = new ArrayList<String>(1);
list.add(filePath.concat(map.get("fileName")));
HttpClientUtil.postFile(list, GlobalContract.FILE_PATH.concat(GlobalContract.POI_RECOMMEND_IMG));

resultVO = new ResultVO();
resultVO.setResData(map);
} else {
resultVO = new ResultVO(GlobalMessage.MSG_01);
}

log.info(GlobalContract.LOG_END);
return JSONObject.fromObject(resultVO).toString();
}
6、GlobalContract常量参考
/**
* 静态变量定义
* @author CJ
*
*/
public class GlobalContract {

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 文件服务器 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/** 文件服务器 —— 测试地址 */
public static final String URL_FILE = "http://121.40.97.206";
/** 文件服务器 —— 请求地址 */
public static final String FILESERVER_URL = URL_FILE + ":9010/fileServer-web/fileUpload";
/** 文件服务器 —— api请求地址 */
public static final String UPLOAD_URL = FILESERVER_URL + "/upload";
/** 本地 文件保存路径 */
public static final String FILEPATH_URL = "d://IMGNFS/cartrip_cms/";
/** 文件存放总目录 */
public static final String FILE_PATH = "/cartrip";
/** 七牛服务器(访问) */
public static final String URL_IMG = "http://oaaiy0zk4.bkt.clouddn.com" + FILE_PATH;
/** POI热门推荐图路径*/
public static final String POI_RECOMMEND_IMG = "/poi_recommend_img/";

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 日志 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/** 日志开始 */
public static final String LOG_BEGIN = "begin";
/** 日志结束 */
public static final String LOG_END = "end";

}

7、FileOptionUtil工具类代码
@Component("fileutil")
public class FileOptionUtil {

/**
* 获取订单号
*
* @return
* @throws Exception
*/
public synchronized static String getfileName() {

long date = System.currentTimeMillis() / 10;
if (GlobalContract.COUNT == 999) {
GlobalContract.COUNT = 100;
} else {
GlobalContract.COUNT++;
}
return date + "" + GlobalContract.COUNT + "";
}

/**
* 将字符输入到文件(不存在则创建,存在则覆盖)
*
* @param content
*/
public String writeFileByBybeBuffer(String content, String docname,
String title) {
FileOutputStream out = null;
FileChannel fcOut = null;
try {
// 获取源文件和目标文件的输入输出流
File file = new File(GlobalContract.FORUM_FILEPATH_URL + docname);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
out = new FileOutputStream(file);
// 获取输入输出通道
fcOut = out.getChannel();

ByteBuffer buffer = ByteBuffer
.wrap(("<!doctype html>"
+"<html>"
+"<head>"
+"<title>"
+ title
+ "</title>"
+"<meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">"
+ "<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />"
+ "<meta name=\"format-detection\" content=\"telephone=no\"/>"
+ "<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />"
+"</head>"
+"<body>"
+ content
+"</body>"
+"</html>")
.getBytes("UTF-8"));

buffer.flip();
// 从输入通道中将数据读到缓冲区
// flip方法让缓冲区可以将新读入的数据写入另一个通道
buffer.clear();
fcOut.write(buffer);
out.flush();
return docname;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fcOut.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}

/**
* 将字符输入到文件(不存在则创建,存在则覆盖) 注:修改时不再添加<meta>标签
*
* @param content
*/
public String updateFileByBybeBuffer(String content, String docname) {

FileOutputStream out = null;
FileChannel fcOut = null;
try {
// 获取源文件和目标文件的输入输出流
File file = new File(GlobalContract.FORUM_FILEPATH_URL + docname);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
out = new FileOutputStream(file);
// 获取输入输出通道
fcOut = out.getChannel();
ByteBuffer buffer = ByteBuffer.wrap(content.getBytes("UTF-8"));
buffer.flip();
// 从输入通道中将数据读到缓冲区
// flip方法让缓冲区可以将新读入的数据写入另一个通道
buffer.clear();
fcOut.write(buffer);
out.flush();
return docname;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fcOut.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}

/**
* 上传图片
*
* @param content
*/
public String writeFileByBybeimg(InputStream in, String path, String name) {

FileOutputStream fos = null;
try {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
String filename = FileOptionUtil.getfileName();
name = name.substring(name.lastIndexOf(".") + 1, name.length());
System.out.println(name);
fos = new FileOutputStream(path + filename + "." + name);
byte[] b = new byte[1024];
while ((in.read(b)) != -1) {
fos.write(b);
}
fos.flush();
return filename + "." + name;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}

/**
* 将文件中的内容读取到字符中
*
* @param content
*/
public static String readFileByBybeBuffer(String docname) {

InputStreamReader read = null;
try {
String encoding = "UTF-8";
File file = new File(GlobalContract.FORUM_FILEPATH_URL + docname);

// File file = new File("http://121.43.144.102:8099/forum_html/146589218504542.html");

read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
StringBuffer lineTxt = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
lineTxt.append(line);
}

// System.out.println("文本内容:" + lineTxt.toString());
return lineTxt.toString();

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}

public static long getTime() {
return System.currentTimeMillis();
}

public static void main(String[] args) {
System.out.println(readFileByBybeBuffer(""));
}

}8、UploadFileUtil工具类代码
/**
* 上传文件util
* @author yangliang
* @time 2017年12月27日下午1:06:18
*/
public class UploadFileUtil {

/**
* 文件保存到本地tomcat
* @author yangliang
* @time 2017年12月27日下午1:21:26
* @param mFile
* @param name 文件名
* @param filePath 保存路径
* @param url 预览地址
* @return
* @throws Exception
*/
public static Map<String, String> uploadFile(MultipartFile mFile, String name, String filePath, String url) throws Exception{

Map<String, String> map = null;

String fileName = mFile.getOriginalFilename();
// 文件后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
// 修改后的文件名
fileName = name.concat(suffix);
// 文件路径
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdirs();
}
String path = filePath.concat(fileName);

FileOutputStream fos = new FileOutputStream(new File(path));
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(mFile.getBytes());
bos.close();

map = new HashMap<String, String>(2);
map.put("fileName", fileName);
map.put("fileUrl", url.concat(fileName));
return map;
}
}9、HttpClientUtil访问接口上传至服务器工具类
/**
* httpClient 上传
* @author CJ
*/
public class HttpClientUtil {

/**
* 上传文件
* @param filePathList 文件路径
* @param filePath 在文件服务器 保存的文件夹名 例:“/poi_thumbnail/”
* @throws ParseException
* @throws IOException
*/
public static void postFile(List<String> filePathList, String filePath)
throws ParseException, IOException {

CloseableHttpClient httpClient = HttpClients.createDefault();
try {

MultipartEntityBuilder build = MultipartEntityBuilder.create();
build.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
build.setCharset(CharsetUtils.get("UTF-8"));

for (int i = 0; i < filePathList.size(); i++) {
build.addPart("uploadFile" + i,
new FileBody(new File(filePathList.get(i))));
}

build.addPart(
"filePath",
new StringBody(filePath, ContentType.create("text/plain",
Consts.UTF_8)));

// 把一个普通参数和文件上传给下面这个地址 是一个servlet
HttpPost httpPost = new HttpPost(GlobalContract.UPLOAD_URL);
// 以浏览器兼容模式运行,防止文件名乱码。
HttpEntity reqEntity = build.build();
httpPost.setEntity(reqEntity);

// System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
// 发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 打印响应状态
// System.out.println(response.getStatusLine());
// 获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// 打印响应长度
// System.out.println("Response content length: "
// + resEntity.getContentLength());
// 打印响应内容
// System.out.println(EntityUtils.toString(resEntity,
// Charset.forName("UTF-8")));
}
// 销毁
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpClient.close();
}
}

/**
* 下载文件
*
* @param url
* http://www.xxx.com/img/333.jpg * @param destFileName
* xxx.jpg/xxx.png/xxx.txt
* @throws ClientProtocolException
* @throws IOException
*/
public static void getFile(String url, String destFileName)
throws ClientProtocolException, IOException {
// 生成一个httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
File file = new File(destFileName);
try {
FileOutputStream fout = new FileOutputStream(file);
int l = -1;
byte[] tmp = new byte[1024];
while ((l = in.read(tmp)) != -1) {
fout.write(tmp, 0, l);
// 注意这里如果用OutputStream.write(buff)的话,图片会失真,大家可以试试
}
fout.flush();
fout.close();
} finally {
// 关闭低层流。
in.close();
}
httpclient.close();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: