gpt4 book ai didi

javascript - 在提交之前使用 Ajax 上传文件的最佳方法

转载 作者:行者123 更新时间:2023-12-03 02:55:59 24 4
gpt4 key购买 nike

我有一个包含多个字段的表单,还有一个文件上传。我可以上传多个文件。

我还知道可以使用 AJAX 上传文件。因此,我想在填写其他所有字段时使用 ajax 上传文件。但是我该如何链接已经上传的图像呢?并且还阻止图像再次上传?

这是表格:

<form id="form_validation" method="POST" action="{{route('storeexpense')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="description" required>
<label class="form-label">Omschrijving</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="number" class="form-control" name="amount" required>
<label class="form-label">Bedrag</label>
</div>
</div>
<div class="form-group form-float">
@foreach ($types as $type)
@if ($type->id === 1)
<input name="transactiontype" type="radio" id="rdio{{$type->id}}" value="{{$type->id}}" checked />
<label for="rdio{{$type->id}}">{{$type->description}}</label>
@else
<input name="transactiontype" type="radio" id="rdio{{$type->id}}" value="{{$type->id}}" />
<label for="rdio{{$type->id}}">{{$type->description}}</label>
@endif
@endforeach
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="datepicker form-control" name="date" placeholder="Please choose a date..." required>

<!-- <label class="form-label">Datum</label> -->
</div>
</div>
<div class="form-group demo-tagsinput-area">
<div class="form-line">
<input type="text" class="form-control" id="tagsinput" data-role="tagsinput" placeholder="Labels" name="tags" required>

</div>
</div>
<div class="form-group form-float">
<div class="form-line">
@if (count($errors) > 0)
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
<input type="file" name="attachments[]" multiple class="custom-file-control"/>
</div>
</div>


<button class="btn btn-primary waves-effect" type="submit">SAVE</button>
</form>

这是保存表单信息的 PHP 代码:

public function store(UploadRequest $request)
{

// Save new transaction in database
$transaction = new Transaction;
$transaction->description = $request->description;
$transaction->amount = $request->amount;
$input = $request->date;
$format = 'd/m/Y';
$date = Carbon::createFromFormat($format, $input);

$transaction->date = $date;
$transaction->transactiontype_id = $request->transactiontype;
$transaction->user_id = Auth::id();
$transaction->save();

// Put tags in array
$inputtags = explode(",", $request->tags);

// Loop through every tag exists
// EXISTS: get ID
// NOT EXISTS: Create and get ID
foreach ($inputtags as $inputtag)
{
$tag = Tag::firstOrCreate(['description' => $inputtag]);
$transaction->tags()->attach($tag->id); //Put the 2 ID's in intermediate table ('tag_transaction')
}


//Check if there are files
if (!is_null($request->attachments))
{
//Loop through every file and upload it
foreach ($request->attachments as $attachment) {
$filename = $attachment->store('attachments');

// Store the filename in the database with link to the transaction
Attachment::create([
'transaction_id' => $transaction->id,
'path' => $filename
]);
}
}

谢谢,巴特

最佳答案

听起来您想制作一个精美的表单,一旦您选择它就开始上传文件,同时用户可以继续填写表单的其余部分。如果是这样,我会这样做:

实现您的主要文本/数据表单,例如。

<form method="POST" action="/save-data-endpoint.php">
<input name="email" type="text" />
<button type="submit>Submit</button>
</form>

旁边是图像表单。例如。

<form method="POST" class="file-upload-form" action="/save-file.php">
<input name="my-file" type="file" />
<!-- note that we wont show a submit button -->
</form>

对于用户来说,这一切看起来都是相同的表单,但单击提交按钮只会将数据发送到 save-data-endpoint.php。现在我们需要一些 js 来控制这种疯狂(为简洁起见,我将使用 jQuery)。但是你可以在js中使用FileReader api,ajax进度跟踪,让它变得更奇特。请参阅https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications了解更多。

$(function(){ // run when document is ready
// listen when the input changes (when a file is selected)
$('.file-upload-form').on('change', function(e){
// file has been selected, submit it via ajax
// show some kind of uploading indication, eg. a spinner
$.ajax({
type:'POST',
url: $(this).attr('action'),
data: new FormData(this),
cache:false,
contentType: false,
processData: false,
success:function(data){
// the save-file.php endpoint returns an id and/or a url to the saved/resized/sanitized image
console.log(data.id, data.url);
// we then inject this id/url, into the main data form
var $hiddenInput = $('<input type="hidden" name="uploads[]" value="'+data.id+'">');
$('.main-form').append($hiddenInput);

// show a thumbnail maybe?
var $thumbnail = $('<img src="'+data.url+'" width="20" height="20" />');
$('.main-form').append($thumbnail);

// hide spinner
// reactivate file upload form to choose another file
$('.file-upload-form').find('input').val('');
},
error: function(){
console.log("error");
}
});
});
});

您的后端将一张一张地获取选择的图像。然后保存它们并返回图像的 id 和/或 url,以便在 js 的成功处理程序中使用。添加一些图像后,您的主表单应如下所示:

<form method="POST" action="/save-data-endpoint.php">
<input name="email" type="text" />
<button type="submit>Submit</button>

<input type="hidden" name="uploads[]" value="x">
<img src="...x.jpg" width="20" height="20" />
<input type="hidden" name="uploads[]" value="y">
<img src="...y.jpg" width="20" height="20" />
</form>

现在,当用户填写剩余字段并单击“提交”时,您的服务器将获取所有数据以及名为 uploads 的数组,其中包含您已保存的所有图像 ID/路径。您现在可以存储此数据并将其与文件关联。

我不会深入讨论后端,因为它可以用任何语言实现。总之,基本流程是:

  • 一次将一个文件发送到保存文件端点,该端点返回文件标识符(可以是 ID、哈希值、图像的完整路径等)
  • js 将这些 id 注入(inject)主表单
  • 主表单提交到保存数据端点,该端点返回成功或错误消息,并存储+关联您首选存储方法中的所有数据。

希望对你有帮助!

关于javascript - 在提交之前使用 Ajax 上传文件的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47622574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com