我正在为我的图片上传功能使用FineUploader插件,而且在启用multiple
选项时,我无法找到跟踪文件索引的方法。
我在处理图像上传时在服务器端做的是,我会查询数据库中的现有图像,获取计数,并保存新上传图像的链接,索引等于existing_count+1
数据库。
这应该允许我记录所有上传的图像,并将其上传顺序作为索引。
但是,启用multiple
选项后,当上传者访问后续文件的服务器端点时,数据库查询似乎不会从上次保存图像更新。
这是竞争条件吗?有没有办法将文件索引传递给服务器?
以下是我的代码:
服务器端(Laravel)
public function save_listing_picture() {
if (Input::hasFile('listing')) {
$user = Auth::user();
$id = $user->id;
$existing_count = Image::where('user_id', $id)->count(); //this doesn't update on a multiple upload request
$file = Input::file('listing');
$imagePath = '/images/'+$id+'/image_'+$existing_count+1+'.jpg';
$img = Image::make($file)->encode('jpg', 75);
$img->save($imagePath);
$imgRecord = new Image();
$imgRecord->link = $imagePath;
$imgRecord->save();
}
}
前端(JS):
var listingUploader = new qq.FineUploader({
element: document.getElementById("image-uploader"),
template: 'qq-template',
debug: true,
request: {
endpoint: '/account/save-image',
params: {'_token': csrf_token},
inputName: 'listing'
},
thumbnails: {
placeholders: {
waitingPath: '/img/fine-uploader/waiting-generic.png',
notAvailablePath: '/img/fine-uploader/not_available-generic.png'
}
},
image: {
minHeight: 300,
minWidth: 300
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
itemLimit: 3
}
});
答案 0 :(得分:1)
我最终使用UUID
来跟踪上传的每个文件,以避免重复和错误覆盖(感谢@RayNicholus提供的建议)。
这是我的解决方案:
服务器端
public function save_listing_picture(Request $request) {
if (Input::hasFile('listing')) {
$user = Auth::user();
$id = $user->id;
$file = Input::file('listing');
$fileId = $request->get('qquuid');
$destination_path = 'images/' . $id . '/';
if (!is_dir($destination_path)) {
mkdir($destination_path, 0777, true);
}
$full_path = $destination_path . $fileId . ".jpg";
$img = Image::make($file)->encode('jpg', 75);
$img->save(public_path() . '/' . $full_path);
$imgRecord = new Image();
$imgRecord->link = $full_path;
$imgRecord->save();
return response()->json(['success' => true]);
}
return response()->json(['status' => 'Input not found']);
}
前端:
var userId = {{Auth::user()->id}}; //laravel blade
var listingUploader = new qq.FineUploader({
element: document.getElementById("image-uploader"),
template: 'qq-template',
debug: true,
request: {
endpoint: '/account/save-image',
params: {'_token': csrf_token},
inputName: 'listing'
},
thumbnails: {
placeholders: {
waitingPath: '/img/fine-uploader/waiting-generic.png',
notAvailablePath: '/img/fine-uploader/not_available-generic.png'
}
},
image: {
minHeight: 300,
minWidth: 300
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
itemLimit: 3
},
callbacks: {
onAllComplete: function(succeeded, failed) {
if (succeeded.length > 0) {
succeeded.forEach(function(fileId, index) {
var imageId = "image" + index;
document.getElementById(imageId).src='images/' + userId + '/' + listingUploader.getUuid(fileId)+".jpg";
});
}
}
}
});