我正在为我的图片上传功能使用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
}
});发布于 2016-10-28 00:25:37
我最终使用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";
});
}
}
}
});https://stackoverflow.com/questions/40281948
复制相似问题