抽空搞了一波微信小程序,刚好弄了个文件上传,完成后分享出来,避免以后踩坑
1.前端微信小程序处理前端上传
微信小程序里面的上传分为文件选择和文件上传,首先文件上传代码如下:
<!--pages/upload/upload.wxml-->
<button class='btn' bindtap='bindChooiceProduct'>发布</button>
接下来是js代码:
/**
* 自定义函数
*/
bindChooiceProduct: function () {
var that = this;
wx.chooseImage({
count: 3, //最多可以选择的图片总数
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
console.log("tempFilePaths: " + tempFilePaths);
//启动上传等待中...
wx.showToast({
title: '正在上传...',
icon: 'loading',
mask: true,
duration: 10000
})
var uploadImgCount = 0;
for (var i = 0, h = tempFilePaths.length; i < h; i++) {
//文件上传代码
}
}
});
}
上一步文件选择好了之后,之后就开始给java后台上传文件啦:
wx.uploadFile({
url: "http://127.0.0.1:8080/fileUpload/upload",
filePath: tempFilePaths[i],
name: 'file',
formData: {
'imgIndex': i
},
header: {
"Content-Type": "multipart/form-data"
},
success: function (res) {
var filename = res.data;
console.log("filename: " + filename);
//如果是最后一张,则隐藏等待中
if (uploadImgCount == tempFilePaths.length) {
wx.hideToast();
}
},
fail: function (res) {
wx.hideToast();
wx.showModal({
title: '错误提示',
content: '上传图片失败',
showCancel: false,
success: function (res) { }
})
}
});
此时前端准备完毕,开始后台吧
JAVA 后台使用 springboot 整合fastdfs,完成整个上传流程:
首先配置文件如下,建立 application.yml 在 resource下:
# 分布式文件系统FDFS配置
fdfs:
soTimeout: 1500 #socket连接超时时长
connectTimeout: 600 #连接tracker服务器超时时长
resHost: 169.254.197.129
thumbImage: #缩略图生成参数,可选
width: 150
height: 150
trackerList: 169.254.197.129:22122 #你的 tracker 所在服务器ip加端口
接下来搞一搞工具类吧,定义
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class FdfsConfig {
@Value("${fdfs.resHost}")
private String resHost;
public String getResHost() {
return resHost;
}
public void setResHost(String resHost) {
this.resHost = resHost;
}
}
作为之后返回给前端的配置
搞一搞上传fastdfs吧:
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
/**
* 工具类
*/
@Component
public class FastDFSClientWrapper {
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private FdfsConfig fdfsConfig;
public String uploadFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile((InputStream)file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
return getResAccessUrl(storePath);
}
/**
* 封装文件完整URL地址
* @param storePath
* @return
*/
private String getResAccessUrl(StorePath storePath) {
String fileUrl = fdfsConfig.getResHost() + "/" + storePath.getFullPath();
return fileUrl;
}
}
工具准备好了,整一下接收前端传值的 controller 吧:
import com.luckysite.util.FastDFSClientWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
/**
* 上传图片到fastdfs
*/
@RestController
@RequestMapping("/fileUpload")
public class FileUploadController {
private Logger log = LoggerFactory.getLogger(FileUploadController.class);
@Autowired
private FastDFSClientWrapper fastDFSClientWrapper;
@PostMapping("/upload")
public String fdfsUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:/upload/uploadStatus";
}
try {
String fileUrl= fastDFSClientWrapper.uploadFile(file);
log.info("FileUploadController-fdfsUpload-上传文件返回地址:" + fileUrl);
return fileUrl;
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/upload/uploadStatus";
}
}
这样就搞定了~
其实挺简单,但是在摸索的过程中还是挺多坑的,如果想要了解fastdfs在Linux环境下安装的可以看看下面的文章:
https://blog.csdn.net/mahongb/article/details/83758579
不定期技术文章