springboot和fastdfs实现文件ajax上传

1.下载:
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.25.4-RELEASE</version>
</dependency>

2.添加配置文件在application.properties中添加:

#读取inputsream阻塞时间
fdfs.so-timeout=3500
fdfs.connect-timeout=6000
#设置缩略图尺寸
fdfs.thumbImage.width=150
fdfs.thumbImage.height=150
#tracker地址
fdfs.trackerList[0]=192.168.6.24:22122
#fdfs.trackerList[1]=192.168.0.202:22122
#通过nginx 访问地址
fdfs.webServerUrl=http://192.168.6.24:8977/
#获取连接池最大数量
fdfs.pool.max-total=200


引入配置:

@ComponentScan(value={"com.github.tobato.fastdfs.service"})
@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastDfsConfig {
}


3.后台代码实现:

package com.tms.bean.system.client;

import com.github.tobato.fastdfs.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;

/**
* fastclent
* Created by gjp on 2017/9/19.
*/
@Component
public class FastDFSClient {
private final Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

@Autowired
private FastFileStorageClient storageClient;

@Autowired
private FdfsWebServer fdfsWebServer;

/**
* 上传文件
* @param file 文件对象
* @return 文件访问地址
* @throws IOException
*/
public String uploadFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
return getResAccessUrl(storePath);
}


/**
* 上传文件
* @param file 文件对象
* @return 文件访问地址
* @throws IOException
*/
public String uploadFileStream(InputStream is,long size,String fileName) throws IOException {
StorePath storePath = storageClient.uploadFile(is,size, FilenameUtils.getExtension(fileName),null);
return getResAccessUrl(storePath);
}

/**
* 上传文件
* @param file 文件对象
* @return 文件访问地址
* @throws IOException
*/
public String uploadFile(File file) throws IOException {
FileInputStream inputStream = new FileInputStream (file);
StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),null);
return getResAccessUrl(storePath);
}

/**
* 将一段字符串生成一个文件上传
* @param content 文件内容
* @param fileExtension
* @return
*/
public String uploadFile(String content, String fileExtension) {
byte[] buff = content.getBytes(Charset.forName("UTF-8"));
ByteArrayInputStream stream = new ByteArrayInputStream(buff);
StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
return getResAccessUrl(storePath);
}

// 封装图片完整URL地址
private String getResAccessUrl(StorePath storePath) {
String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
return fileUrl;
}

/**
* 删除文件
* @param fileUrl 文件访问地址
* @return
*/
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
return;
}
try {
StorePath storePath = StorePath.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (FdfsUnsupportStorePathException e) {
logger.warn(e.getMessage());
}
}


/**
* 图片缩略图
* @param is
* @param size
* @param fileExtName
* @param metaData
* @return 文件访问地址
返回地址为:http://192.168.6.24:8977/group1/M00/00/00/wKgGGFnDGS-AVhrAAAMhasozgRc678.jpg
访问缩略图地址为:http://192.168.6.24:8977/group1/M00/00/00/wKgGGFnDGS-AVhrAAAMhasozgRc678_150x150.jpg
*/
public String upfileImage(InputStream is,long size,String fileExtName,Set<MateData> metaData){
StorePath path = storageClient.uploadImageAndCrtThumbImage(is,size,fileExtName,metaData);

return getResAccessUrl(path);
}


}


4.controller 实现:
package com.tms.controller.system;

import com.tms.bean.system.client.FastDFSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
* 文件上传
* Created by gjp on 2017/9/19.
*/
@Controller
@RequestMapping("/file")
public class FileUpController {

private static final Logger fLog = LoggerFactory.getLogger(FileUpController.class);
@Resource
private FastDFSClient fastDFSClient;

/**
*
* @param multipartFile
* @return
*/
@ResponseBody
@RequestMapping(value = "/up",method = RequestMethod.POST)
public Map<String,String> fileUp(MultipartHttpServletRequest multipartFile, HttpServletRequest request){

Map<String,String> result = new HashMap<String,String>();
String param = request.getParameter("param");//参数名称
if(StringUtils.isEmpty(param)){
result.put("result","false");
result.put("msg","请添加参数");
}
InputStream is = null;

String fileName = multipartFile.getFile(param).getOriginalFilename();
try {
long size = multipartFile.getFile(param).getSize();
is = multipartFile.getFile(param).getInputStream();
String path = fastDFSClient.uploadFileStream(is,size,fileName);
result.put("result","true");
//图片地址
result.put("srckey",path);
}catch (IOException e){
result.put("result","false");
fLog.error("file:"+fileName,e.fillInStackTrace());
}finally {
if (is !=null){
try {
is.close();
}catch (IOException io){
fLog.error(io.getMessage());
}
}
}

return result;
}

}


5.前台页面实现:

<li>
<span class="reg_label2 rt50 relativeBox"><span class="red_font">*</span>营业执照:</span>
<span class="upload_span relativeBox">
<input type="file" id="id_license" class="input_file absoluteBox notnull" name="license" />
<img src="" id="id_license_img" />
<input type="hidden" id="id_license_value" name="licenseName" />
</span>
</li>



$("#id_license").on("change", function(){
$.ajaxFileUpload({
url: '/file/up', //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'id_license', //文件上传域的ID
dataType: 'json', //返回值类型 一般设置为json
data:{param:'license'},//file 标签的名称
type:'post',
success: function (data, status) //服务器成功响应处理函数
{
if(data.result == "true"){
alert("上传成功!");
$("#id_license_value").val(data.srckey);

var $file = $(this);
var fileObj = $file[0];
var windowURL = window.URL || window.webkitURL;
var dataURL;
var $img = $("#id_license_img");

if (fileObj && fileObj.files && fileObj.files[0]) {
dataURL = windowURL.createObjectURL(fileObj.files[0]);
$img.attr('src', dataURL);
} else {
dataURL = $file.val();
var imgObj = document.getElementById("preview");
imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
}

}else {
alert("上传失败!");
}
},error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
}
})

});

引入js

<script src="../../static/js/ajaxfileupload.js" th:src="@{/js/ajaxfileupload.js}"></script>

<script src="../../static/js/jquery-1.8.3.min.js" th:src="@{/js/jquery-1.8.3.min.js}"></script>


查看效果:
原图:


[img]http://dl2.iteye.com/upload/attachment/0127/0713/ed6f69d6-ab72-399e-8167-19c26fed4242.png[/img]

缩略图:

[img]http://dl2.iteye.com/upload/attachment/0127/0715/b529d0c5-5055-327b-8008-372de0ff6e2a.png[/img]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值