我正在将文件上传到服务器,并且要将文件名保存到数据库。我可以将其保存到数据库中。我也想将用户名和文件名一起保存,但是问题是我无法将用户名从刀片服务器传递给控制器,因为它不包含在用于上传的按钮上。用户名是一个全局变量,是否有可能将其与表单一起传递给ajax?我需要在代码上添加什么?预先谢谢你!
我尝试过这样传递用户名
data: "refNumber2="+refNumber2+formData,
但它仍未传递refNumber。
这是我用于文件上传的html代码:
<form method="post" action="{{URL::to('/store')}} " enctype="multipart/form-data" id="frmuploadFile" class="frmuploadFile">
<input name="image" type="file" class="image">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button type="submit" name="btn" id="btn-upload" class="btn btn-default col-sm-15">Upload a File</button>
</form>
这是我的ajax:
$('form').on("submit",function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "{{ url ('/store')}}",
type: 'POST',
data: "refNumber2="+refNumber2+formData,
async: true,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function(data){
}
});
});//form
这是我的控制器:
public function store(Request $request){
$refNumber = $request->get('refNumber2');
if (Input::hasFile('image')){
echo "UPLOADED <br>";
$file = Input::file('image');
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'.'.time().'.'.$extension;
$file->move('uploads', $fileNameToStore);
$filename = $file->getClientOriginalName();
}
DB::table('i_di_thread')
->insert(['refNumber'=>$refNumber,'message'=>$fileNameToStore]);
}//Upload File
答案 0 :(得分:0)
只需在from中添加另一个隐藏字段,然后输入全局变量值即可。
<form method="post" action="{{URL::to('/store')}} " enctype="multipart/form-data" id="frmuploadFile" class="frmuploadFile">
<input name="image" type="file" class="image">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
// add another hidden field here
<input type="hidden" name="refNumber2" id="refNumber2" value="{{ your_global_variable }}">
<button type="submit" name="btn" id="btn-upload" class="btn btn-default col-sm-15">Upload a File</button>
</form>
答案 1 :(得分:0)
您可以在此处为用户名命名的另一个隐藏字段添加
<input type="hidden" name="userName" id="userName" value="{{Auth::user()->name}}">
,在您的控制器中,您可以通过
获取它 $request->get('userName')