spring mvc+ajaxfileupload 實現非同步上傳圖片
1.匯入包引入js
匯入spring包以及如下包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.spring.xml配置檔案
<!-- SpringMVC上傳檔案時,需要配置MultipartResolver處理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <!-- 指定所上傳檔案的總大小不能超過200KB。注意maxUploadSize屬性的限制不是針對單個檔案,而是所有檔案的容量之和 -->3.fileupload.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title>檔案上傳</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<body>
<body>
<div >
<form modelAttribute="uploadInfo" id="uploadForm" name="uploadForm" action="bg/upload" method="post">
<div id="fileuploaddiv">
上傳檔案:<input type="file" id="apkFile" name="file"/>
<input type="button" value="上傳" onclick="ajaxFileUpload('apkFile','apkFileTip','img','filename','fileuploaddiv')"/>
<input type="text" id="filename" name="filename"/>
<span id="apkFileTip" style="width:250px"></span>
</div>
<div class="">
<button type="submit" class="btn">提交</button>
</div>
<form>
</div>
</body>
<script type="text/javascript">
/*
*fileid上傳input id
*resulttip 返回結果
*type 上傳型別
*returnfileurl 成功上傳後的檔案路徑
*/
var num =1;
function ajaxFileUpload(fileid, resulttip, type, returnfileurl,fileuploaddiv)
{
var fileiddata = $('#'+fileid).val();
if(fileiddata == null || fileiddata ==''){
$('#'+resulttip).html('請選擇檔案');
return false;
}else if (type == 'img'){
if (!/\.(jpg|jpeg|png|JPEG|JPG|PNG)$/.test(fileiddata)){
alert("圖片型別必須是.jpeg,jpg,png中的一種");
$('#'+fileid).val("");
return false;
}
}
//firefox獲取的是檔名,IE獲取的是全路徑名,正則表示式擷取檔名,判斷檔名的長度
var arrdata = fileiddata.split(/\\/);
if(arrdata[arrdata.length-1].length >30){
$('#'+resulttip).html('檔名超過限定30字元的長度');
$('#'+fileid).val("");
return false;
}
$('#'+resulttip).html('檔案上傳中');
$.ajaxFileUpload
(
{
url:'file/fileupload',//用於檔案上傳的伺服器端請求地址
secureuri:false,//一般設定為false
fileElementId:fileid,//檔案上傳空間的id屬性 <input type="file" id="file" name="file" />
dataType: 'json',//返回值型別 一般設定為json
type : 'POST',
timeout:1200000, // 超時校驗 120秒超時
success: function (data) //伺服器成功響應處理函式
{
if(data.result=='suc'){
$('#'+resulttip).html('新增成功');
$('#'+fileid).val("");
if($('#'+returnfileurl).val() == null || $('#'+returnfileurl).val() ==''){
$('#'+returnfileurl).val(data.filename);
}else{
$('#'+returnfileurl).val($('#'+returnfileurl).val()+","+data.filename);
}
if(type == 'img'){
$('#'+fileuploaddiv).append("<div id='filediv"+num+"'>檔案:"+fileiddata+"<a href='javascript:void(0)' onclick='filedelete(\"filediv"+num+"\",\""+returnfileurl+"\",\""+data.filename+"\")'>刪除</a><br/></div>");
num=num+1;
}
return false;
}else if(data.result=='fnull'){
$('#'+resulttip).html('上傳的檔案不是圖片型別的檔案');
$('#'+fileid).val("");
}else if(data.result=='size2big'){
$('#'+resulttip).html('檔案尺寸超過限制,尺寸界定在2560*10240範圍內');
$('#'+fileid).val("");
}else if(data.result=='file2big'){
$('#'+resulttip).html('檔案大小超過限制,大小界定在10M範圍內');
$('#'+fileid).val("");
}else if(data.result=='exe'){
$('#'+resulttip).html('檔案格式不支援');
$('#'+fileid).val("");
}else{
$('#'+resulttip).html('新增失敗');
$('#'+fileid).val("");
}
},
error: function (data, status, e)//伺服器響應失敗處理函式
{
if('SyntaxError: illegal character' == e){
$('#'+result).html('檔案大小超過限制');
$('#'+item).val("");
}else if('SyntaxError: syntax error' == e){
$('#'+result).html('檔案上傳有誤');
$('#'+item).val("");
}else if('SyntaxError: 語法錯誤' == e){
$('#'+result).html('檔案大小超過限制');
$('#'+item).val("");
}else{
$('#'+result).html('上傳超時');
$('#'+item).val("");
}
}
}
)
return false;
}
function filedelete(filedivnum,returnfileurl,fileName){
var returnfileurlvalue = $("#"+returnfileurl).val();
returnfileurlvalue = returnfileurlvalue.replace(","+fileName,"");
returnfileurlvalue = returnfileurlvalue.replace(fileName,"");
$("#"+returnfileurl).val(returnfileurlvalue);
$("#"+filedivnum).remove();
$.ajax({
url : 'file/filedelete',
type : 'POST',
dataType : 'json',
data:{fileName:fileName},
async : false,
error : function() {
alert('Operate Failed!');
},
success : function(data) {
if (data.result=='suc'){
//alert('刪除成功!');
}
}
});
};
</script>
</html>
4.FileController.java(此處上上傳到阿里雲伺服器)
package com.zhkj.mgmt.user.web;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.zhkj.utils.FileOss;
import com.zhkj.utils.FileUtil;
@Controller
@RequestMapping("/file")
public class FileController {
/**
* 進入圖片上傳頁
*/
@RequestMapping(value="/gofileupload",method= RequestMethod.GET)
public String gofileupload(){
return "fileupload";
}
/**
* ajax上傳圖片
*/
@RequestMapping(value = "/fileupload", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(@RequestParam(required = false) MultipartFile file, final HttpServletRequest request) {
if (file.isEmpty()){
return "{\"result\":\"fail\"}";
}
if(file.getOriginalFilename().endsWith(".exe")){
return "{\"result\":\"exe\"}";
}
//獲取字尾名,轉為小寫儲存
String suffix = (FileUtil.getExtensionName(file.getOriginalFilename())).toLowerCase();
//獲取檔名
String saveName = createDateFileName(suffix);
System.out.println(saveName);
JSONObject result = new JSONObject();
try {
if(file.getContentType().startsWith("image")){
BufferedImage buff = ImageIO.read(file.getInputStream());
if(buff == null){ // 如果上傳的圖片損壞,或者上傳的圖片為改字尾得來的,在轉為圖片流的時候,獲得的圖片流為NULL,再獲取尺寸報空指標
return "{\"result\":\"fnull\"}";
}
if(buff.getWidth() > 2560 || buff.getHeight() > 10240){ //圖片尺寸限制在 2560*10240
return "{\"result\":\"size2big\"}";
}
}
/*if(file.getSize()>(10*1024*1024)){ //檔案上傳控制在10M內,圖片和附件都在控制範圍內: 10*1024*1024
return "{\"result\":\"file2big\"}";
}*/
FileOss.ossuploadFile(saveName, file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.put("result", "fail");
return result.toString();
}
result.put("result", "suc");
result.put("filename", saveName);
return result.toString();
}
public static String createDateFileName(String suffix) {
String returnPath = null;
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileStr = sf.format(new Date())+ new Random().nextInt(10000);
String srcFileName = fileStr + "." + suffix;
String tempPath = srcFileName.substring(0, 4)
+ srcFileName.substring(4, 6) + "/"
+ srcFileName.substring(6, 8) + "/"
+ srcFileName.substring(8, 10) + "/";
returnPath = tempPath + srcFileName;
return returnPath;
}
/**
* ajax上傳圖片
*/
@RequestMapping(value = "/filedelete", method = RequestMethod.POST)
@ResponseBody
public String filedelete(HttpServletResponse response,@RequestParam String fileName) {
JSONObject result = new JSONObject();
try {
FileOss.ossdeleteFile(fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.put("result", "fail");
return result.toString();
}
result.put("result", "suc");
return result.toString();
}
}
相關推薦
spring mvc+ajaxfileupload 實現非同步上傳圖片
1.匯入包引入js 匯入spring包以及如下包 <dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><ve
SpringMVC+ajaxFileUpload 相容IE瀏覽器實現非同步上傳圖片
第一次出差到深圳,幫朋友給一個專案收尾,客戶臨時要求上傳檔案的時候順便上傳封面,所以就想到用非同步上傳的方式,然後在前端預覽上傳的圖片,於是就用到了“ajaxFileUpload”這一款基於“jquery”的上傳外掛,剛拿到手的時候去網上查了一下他的用法,然後理所當然的在返
Spring MVC - MultipartFile實現檔案上傳(單檔案與多檔案上傳)
前提:引入jar包。 <dependency>
js 實現非同步上傳圖片+預覽
兩種js實現方式,一種用原生的ajax;另一種用JQuery,例子比較簡單,直接上程式碼。 <!DOCTYPE html> <html> <head> <title>Title</title> <link h
ajax實現非同步上傳圖片
圖片上傳並回顯是一個最基本的功能,本文只簡單實現了一個demo,並沒有進行復雜的判斷,簡單記錄下操作流程:js中用到了Formdata:FormData物件用以將資料編譯成鍵值對,以便用XMLHttpRequest來發送資料。其主要用於傳送表單資料,但亦可用於傳送帶鍵資料(keyed data)。如果表單en
uploadify結合ThinkPHP5上傳類實現非同步上傳圖片
注:我們使用的是免費的Flash版本①引入必需的檔案jQueryjquery.uploadify-3.1.min.jsuploadify.css②HTML元素的搭建(結合bootstrap)<div class="form-group"> <labe
Spring Mvc poi實現檔案上傳
上傳檔案有很多種方法,這裡主要講通過poi元件(jar包))實現檔案上傳。專案依賴commons-io.jar和commons-fileupload(版本沒有太大要求,能實現功能即可),樓主用的是commons-fileupload-1.3.1.jar和commons
ajaxFileUpload 非同步上傳圖片 使用說明
首先引入 相應的jquery <script src="script/jquery-1.7.1.min.js"></script> <script src="script/ajaxfileupload.js"></script>
spring boot 實現 前段上傳圖片,後臺將圖片轉存的前臺伺服器(FTPClient)
最近做一個增加產品的介面,需要上傳圖片到前臺路徑下就通過前臺FTPClient實現後臺將檔案轉存到前臺伺服器路徑下, public String hostname = "hxxxxxxxxxxx"; //ftp伺服器埠號預設為21 public Integer port
thinkphp+ajaxfileupload 非同步上傳圖片
藉助外掛實現非同步上傳圖片的,需要引用Jquery。 HTML: <a onclick="selectImg(this)">照片</a> <input type="file" id="file{$voc.id}" name="file{$vo
MVC非同步上傳圖片
今天聽黑馬訓練營就業班的MVC課程,馬老師在非同步上傳圖片這裡卡住了半天,多次除錯都無法在後臺控制器獲得圖片。 下面直接寫出MVC中檔案上傳方法。 1.控制器 public ActionResult
jQuery外掛之ajaxFileUpload(非同步上傳圖片並實時顯示,並解決onchange後ajaxFileUpload失效問題)
參考學習: 第一篇:http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html 第二篇:http://www.jb51.net/article/50518.htm 第三篇:http://zhangzhao
SpringMVC中使用ajaxfileupload非同步上傳圖片檔案視訊
摘要:一、在專案中匯入commons-fileupload-1.3.1.jarcommons-io-2.4.jar 兩個jar包,引入專案中。、二、並在Spring-mvc.xml中配置multipart的上傳解析器,這裡上傳的都是通過multipart這個類<!--
ckeditor添加自定義按鈕整合swfupload實現批量上傳圖片
下載 了解 nbsp 文件 mouseover 去掉 dial size pro ckeditor添加自定義按鈕整合swfupload實現批量上傳圖片給ckeditor添加自定義按鈕,由於ckeditor只能上傳一張圖片,如果要上傳多張圖片就要結合ckfinder,而ckf
在fragment中實現Android上傳圖片至本地JavaWeb服務器
prop prefix adt ilo err 1.10 response try 轉換成 服務器端: 需要一個接受文件的servlet,以及導入兩個包:commons-fileupload-1.3.1.jar 和 commons-io-2.4.jar import ja
JavaScript的FormData+Ajax實現檔案上傳+圖片上傳
JavaScript的FormData+Ajax實現檔案上傳+圖片上傳 在很多網頁開發中會存在檔案上傳,圖片上傳的操作,有的使用form表單預設功能提交檔案,有的採用Ajax提交 如果採用form表單的提交方式,恰恰又需要新增額外的引數或者需要設定特定的請求頭資訊,那麼這種方式就
thinkPHP利用ajax非同步上傳圖片並顯示、刪除
近來學習tp5的過程中,專案中有個發帖功能,選擇主題圖片。如下: 利用原始的檔案上傳處理,雖然通過原始js語句能實時顯示上傳圖片,但是這樣的話會涉及很多相容問題。使用ajax技術,實現選擇性刪除所選圖片功能,並不會有相容問題。 表單檔案form: <form method="po
Struts框架上傳下載檔案輔助類,簡單實現Struts上傳圖片以及下載
首先在看這篇文章的前提下,你得會用Struts框架,有一定的基礎瞭解,說白了瞭解怎麼搭建就行了,然後基本就能順利執行本篇文章的Demo,當然這個類不僅僅侷限於圖片上傳下載的,因為是自己用流寫的方法所以可以支援其他檔案上傳下載。
ajax實現非同步上傳檔案
html+js程式碼 <form action="" enctype="multipart/form-data" id="upForm"> {{csrf_field()}} <input type="text" name="name" value="
使用jsJdk非同步上傳圖片至OSS伺服器
阿里雲官方文件中給的基本都是同步上傳檔案的DEMO,可能是非同步的比較簡單,但是由於自己JS基礎還不夠牢固,在學習使用的時候也很鬧心,因為老是看著看著就看到非同步的那邊去了。將自己寫好的的一個DEMO放於部落格中,萬一能夠幫助到任何一個和我一樣的朋友也是好的。 <!DOCTYPE html&