前言
不管是web还是微信小程序又或者uniapp什么的,我总是容易忘记某个环节,然后翻资料。以后翻这篇文章就可以了。
微信小程序与UniAPP之图片上传
微信小程序与uniapp代码几乎一样(创新与腾讯无瓜)。两者代码相同到很多时候把uni改成wx就行了。
选择图片
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths
that.setData({
displaypic: tempFilePaths,
selectpic: tempFilePaths,
style: 'width: 100px; height: 100px; margin-top: 0rem; margin-left: 0rem;'
// cameraText: ''
})
}
})
上传步骤
wx.uploadFile({
url: app.globalData.uploadImgUrl + '/weChatAppletHttpApi/submitTrouble',
filePath: params.selectpic,
name: 'imageFile',
header: {
"Content-Type": "multipart/form-data"
},
formData: {
COMMUNITYID: params.communityId,
TIMESTAMP: timestamp,
FKEY: md5util.md5(params.communityId + '' + timestamp + app.globalData.APP_INTF_SECRECT)
},
success: function (res) {
resolve(res.data)
},
fail: function () {
reject(err)
}
})
web上传图片
利用label特性实现影藏input
html
<label for="fileinp" class="importLabel" v-if="loginType==5">
<button id="importBtn" class="importBtn" >
<img src="../statics/img/svg/import.svg" width="32px" height="32px">
</button>
<input type="file" id="fileinp" accept="image/png, image/jpeg, image/gif, image/jpg" onchange="preview()" title="请上传地图图片">
</label>
css
#fileinp{
position: absolute;
left: 0;
top: 0;
opacity: 0;
}
js
function preview() {
console.log("上传图片");
var f = document.getElementById('fileinp').files[0];
if(f == undefined || f == ''){
return;
}
var reads = new FileReader();
reads.readAsDataURL(f);
reads.onload=function (e) {
var fd = new FormData();
fd.append('imageFile', f);
uploading(fd);
};
}
function uploading(fd) {
$.ajax({
url: "pageapi/mapPicture",
type:"post",
// Form数据
data: fd,
cache: false,
contentType: false,
processData: false,
success:function(data){
if (data.code === 0) {
vm.mapPicture = data.httpUrl;
} else {
alert(data.msg);
}
}
});
}
web多图上传(待)
springBoot后台
@RequestMapping(value = "/submitTrouble", method = RequestMethod.POST)
public R submitTrouble(@RequestParam(value = "imageFile", required = false) MultipartFile imageFile,
@RequestParam Map<String, Object> paraMap){
String communityIdStr = (String)paraMap.get("COMMUNITYID");
String timeStamp = (String)paraMap.get("TIMESTAMP");
if(Tools.checkKey(communityIdStr, timeStamp, paraMap.get("FKEY").toString())) {
if (imageFile == null) {
R.error("图片不能为空");
}
String fileName = imageFile.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!"jpg".equals(suffix) && !"png".equals(suffix) && !"jpeg".equals(suffix)) {
return R.error("图片格式错误");
}
String imageAbsoluteUrl = "";
try{
String faceid = "u_"+SnowflakeIdWorker.generateId();
String imageRelativeUrl = ConfigConstant.BASE_URL + ConfigConstant.TROUBLE_IMAGE_DIR + "/" +faceid+".jpg";
imageAbsoluteUrl = ConfigConstant.createdIpAddress() + ConfigConstant.TROUBLE_IMAGE_DIR + "/" +faceid+".jpg";
imageFile.transferTo(new File(imageRelativeUrl));
}catch (Exception e){
e.printStackTrace();
}
return R.ok("提交成功");
}else {
logger.info("请求参数错误!params:"+paraMap);
return R.error(SystemMessageContents.ErrorCode.MESSAGE_USERS_TOKEN_ERROR, "请求参数错误!");
}
}
还有一个文件工具类,非常好用
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.text.DecimalFormat;
import java.util.Base64;
public class FileUtil {
public static void main(String[] args) {
String dirName = "d:/FH/topic/";// 创建目录
//FileUtil.createDir(dirName);
// String filedir="d://imgs//91f54d03cee94fd7af99db3d45b3610e.apk";
String filedir = "d://imgs//2bb7ac3846704076b1695238adb4a578.mp4";
try {
long size = getFileSizes(new File(filedir));
String m = FormetFileSize(size, "M" );
System.out.println(m);
System.out.println((double) 102400 / 1024);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 判断文件是否存在
*
* @param destDirName 目标目录名
* @return 目录创建成功返回true,否则返回false
*/
public static boolean hasFileExists(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
return true;
}
return false;
}
/**
* 创建目录
*
* @param destDirName 目标目录名
* @return 目录创建成功返回true,否则返回false
*/
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
return true;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
// 创建单个目录
if (dir.mkdirs()) {
return true;
} else {
return false;
}
}
/**
* 删除文件
* @param filePathAndName String 文件路径及名称 如c:/fqf.txt
* @return boolean
*/
public static void delFile(String filePathAndName) {
try {
if (hasFileExists(filePathAndName)) {
java.io.File myDelFile = new java.io.File(filePathAndName);
myDelFile.delete();
}
} catch (Exception e) {
System.out.println("删除文件操作出错" );
throw e;
}
}
/**
* 读取到字节数组0
*
* @param filePath //路径
* @throws IOException
*/
public static byte[] getContent(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("file too big..." );
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
// 确保所有数据均被读取
if (offset != buffer.length) {
throw new IOException("Could not completely read file " + file.getName());
}
fi.close();
return buffer;
}
/**
* 读取到字节数组1
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray(String filePath) throws IOException {
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException(filePath);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
/**
* 读取到字节数组2
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray2(String filePath) throws IOException {
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException(filePath);
}
FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
// System.out.println("reading");
}
return byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray3(String filePath) throws IOException {
FileChannel fc = null;
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(filePath, "r" );
fc = rf.getChannel();
MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();
// System.out.println(byteBuffer.isLoaded());
byte[] result = new byte[(int) fc.size()];
if (byteBuffer.remaining() > 0) {
// System.out.println("remain");
byteBuffer.get(result, 0, byteBuffer.remaining());
}
return result;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
rf.close();
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*** 获取文件大小 ***/
@SuppressWarnings("resource" )
public static long getFileSizes(File f) throws Exception {
long s = 0;
if (f.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(f);
s = fis.available();
} else {
f.createNewFile();
System.out.println("文件不存在" );
}
return s;
}
/*** 转换文件大小单位(b/kb/mb/gb) ***/
public static String FormetFileSize(long fileS, String kind) {// 转换文件大小
DecimalFormat df = new DecimalFormat("#.0" );
String fileSizeString = "";
if (kind.equals("B" )) {
fileSizeString = df.format((double) fileS) + "B";
} else if (kind.equals("K" )) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (kind.equals("M" )) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else if (kind.equals("G" )) {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
public static String getFileNameByDate() {
String filename = "";
return filename;
}
/**
* 转base64字符串
* @return
* @throws IOException
*/
public static String toBase64(String filePath) throws IOException {
return Base64.getEncoder().encodeToString(toByteArray3(filePath));
}
/**
* 将源文件 拷贝到新的文件目录下
* @param sourcePath
* @param newPath
*/
public static void copyFile(String sourcePath, String newPath) {
File start = new File(sourcePath);
File end = new File(newPath);
try(BufferedInputStream bis=new BufferedInputStream(new FileInputStream(start));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(end))) {
int len = 0;
byte[] flush = new byte[1024];
while((len=bis.read(flush)) != -1) {
bos.write(flush, 0, len);
}
bos.flush();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}
//删除文件和目录
public static void clearFiles(String workspaceRootPath){
File file = new File(workspaceRootPath);
if(file.exists()){
deleteFile(file);
}
}
public static void deleteFile(File file){
if(file.isDirectory()){
File[] files = file.listFiles();
for(int i=0; i<files.length; i++){
deleteFile(files[i]);
}
}
file.delete();
}
}