I'm trying to allow users to upload an image to my site. I found a demo but it is written in PHP. I am using CSHTML in Webmatrix, and it doesn't seem to be compatible with the PHP file. Does anyone have any resources, recommendations, or links to information for writing a similar code as below but in a compatible format to Webmatrix/ASP.NET? Also, is there a way to rename the file when it's uploaded and save it to a certain location?
Are there any security precautions I should take when allowing users to upload to the site?
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}
else {
// form submit
$files = $_FILES['fileselect'];
foreach ($files['error'] as $id => $err) {
if ($err == UPLOAD_ERR_OK) {
$fn = $files['name'][$id];
move_uploaded_file(
$files['tmp_name'][$id],
'uploads/' . $fn
);
echo "<p>File $fn uploaded.</p>";
}
}
}
use fileupload.js
<script src="@Url.Content("/Scripts/jquery.fileupload.js")" type="text/javascript"></script>
<input type="file" name="resume" onchange="onChangeResume()" id="txtImageUpload" style="width: 76px;" />
function onChangeResume(){
$('#txtImageUpload').fileupload({
dataType: 'json',
url: '/CandidateManagement.aspx/ImageUpload',
autoUpload: true,
done: function (e, data) {
//Statements
}
});
}
code behind
HttpPostedFileBase resume = Request.Files["txtImageUpload"];
if (resume != null && resume.ContentLength > 0)
{
var fileName = Path.GetFileName(resume.FileName);
var path = Path.Combine(Server.MapPath("~/Resumes"), fileName);//you can give what ever you want
resume.SaveAs(path);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.