文件的上传下载(非原创),来源于 http://gjp014.iteye.com/blog/2393836
springboot和fastdfs实现文件ajax上传
博客分类:springboot+fdfs文件上传下载
1.下载:
com.github.tobato
fastdfs-client
1.25.4-RELEASE
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 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.前台页面实现:
- *营业执照:
$("#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