<body>
<form id="form1" modelAttribute="uploadForm" enctype="multipart/form-data">
<label for="sampleText">Please enter a text </label>
<input id="sampleText" name="sampleText" type="text" /> <br/>
,
<label for="sampleFile">Please select a file</label>
<input id="sampleFile" name="files[0]" type="file" style="border: solid 1px black" /> <br/>
<label for="sampleFile1">Please select a file</label>
<input id="sampleFile1" name="files[1]" type="file" style="border: solid 1px black" /> <br/>
<input id="uploadBtn" type="button" value="Ajax Submit" onClick="Checkfiles();"></input>
</form>
<script type="text/javascript">
function Checkfiles()
{
var fup = document.getElementById('sampleFile');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc" || ext == "txt")
{
performAjaxSubmit();
}
else
{
alert("Upload Gif or Jpg images only");
fup.focus();
return false;
}
}
function performAjaxSubmit() {
var sampleText = document.getElementById("sampleText").value;
var sampleFile = document.getElementById("sampleFile").files[0];
var sampleFile1= document.getElementById("sampleFile1").files[1];
var formdata = new FormData();
formdata.append("files[0]", sampleFile);
formdata.append("files[1]", sampleFile1);
var xhr = new XMLHttpRequest();
xhr.open("POST","save.html", true);
xhr.send(formdata);
xhr.send(formdata);
}
</script>
in the controller side
#RequestMapping( value = "/save", method = RequestMethod.POST )
public String save( #ModelAttribute( "uploadForm" ) FileUploadForm uploadForm,
BindingResult result,
Model map ) throws IllegalStateException, IOException
{
List<MultipartFile> files = uploadForm.getFiles();
List<String> fileNames = new ArrayList<String>();
if( null != files && files.size() > 0 )
{
for( MultipartFile multipartFile : files )
{
if( multipartFile.getSize() > 0 )
{
}
InputStream inputStream = null;
inputStream = multipartFile.getInputStream();
if( multipartFile.getSize() > 10000 )
{
System.out.println( "File Size exceeded:::" + multipartFile.getSize() );
}
String fileName = multipartFile.getOriginalFilename();
fileNames.add( fileName );
System.out.println( fileName );
//Handle file content - multipartFile.getInputStream()
File dest = new File( "C:/Aslam/files/" + fileName );
multipartFile.transferTo( dest );
}
}
System.out.println( "save.html is called" );
map.addAttribute( "files",
fileNames );
return "file_upload_success";
}
The requirement is to use ajax with spring without submitting the form, but the problem in the above code is that files[1] is not saved,
I am not sure whats happening - either xhr is not passing the files[1] to the controller or controller is not reading the files[1]
Please somebody help me i am new to ajax
The following code worked for me using Apache file upload ..
In Javascript
var fd = new FormData();
fd.append('file',packageFile);
fd.append('file',xmlFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() { });
xhr.send(fd);
In Spring contoller
public String save(HttpServletRequest request, HttpServletResponse httpServletResponse) {
boolean isMultipart;
String response = null;
String myFileName = null;
String filename = null;
isMultipart = ServletFileUpload.isMultipartContent(request);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
InputStream in = fi.getInputStream();
filename = UPLOAD_FILE_DIR + sessionId + "/" + fi.getName();
if (filename.endsWith(".zip")) {
myFileName = fi.getName();
} else if(filename.endsWith(".xml")) {
myFileName = fi.getName();
}
File fd = new File(UPLOAD_FILE_DIR + sessionId + "/" + myFileName);
final File parent_directory = fd.getParentFile();
FileOutputStream fos = new FileOutputStream(fd);
byte[] buffer = new byte[4096];
int length;while ((length = in.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
}
}
EDIT: The following is the Javascript code to get the selected files and adding them to FormData
packageFile = $.find(".fileselector")[0].files[0];
xmlFile = $.find(".fileselector")[1].files[0];
var fd = new FormData();
fd.append('file',packageFile);
fd.append('file',xmlFile);
Following is my XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() { });
xhr.send(fd);
Below is the HTML tags for uploading files
<input id="upf_local_fileinput1" type="file" name="myFile" path="fileData" class="fileselector">
<input id="upf_local_fileinput2" type="file" name="myFile" path="fileData" class="fileselector">
Try the below code if you still have problem because I remember that in some version of Spring the above code didn't worked.
MultipartHttpServletRequest multi = (MultipartHttpServletRequest) request;
Map fileMap = multi.getFileMap();
Iterator fileIt = fileMap.keySet().iterator();
while (fileIt.hasNext()) {
String fileKey = (String) fileIt.next();
MultipartFile file = (MultipartFile) fileMap.get(fileKey);
if (file != null) {
bufReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
} else {
System.out.println("Invalid file");
}
String str;
File file = new File(imeiFilePath);
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
while ((str = bufReader.readLine()) != null) {
if (bw != null) {
bw.write(str);
bw.newLine();
}
}
if (bw != null) {
bw.flush();
bw.close();
}
}
Related
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create([Bind]Employee employee)
{
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
foreach (var Image in files)
{
if (Image != null && Image.Length > 0)
{
var file = Image;
var uploads = Path.Combine(_appEnvironment.WebRootPath, "uploads\\img");
if (file.Length > 0)
{
var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
employee.ImageName = fileName;
}
}
}
}
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Edit", new { id = employee.Id,name=employee.FirstName});
}
else
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
}
return View(employee);
}
when i save image, image save successfully in database, but it takes full image path like this C:\Users\VIZO\Desktop\employee.jpg i dont want like this, i need to save image path somehting like this ~images\employee.jpg and in specific folder and same path should save in database, also if someone show me after saving correct path how i can view that image.
You need to create and save that path which can work in browser. like this
"uploads/img/" + fileName
fileName which you create at run time.
Action Method Updated
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create([Bind]Employee employee)
{
string uploadPath = "uploads/img";
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
foreach (var file in files)
{
if (file != null && file.Length > 0)
{
var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
var uploadPathWithfileName = Path.Combine(uploadPath, fileName);
var uploadAbsolutePath = Path.Combine(_appEnvironment.WebRootPath, uploadPathWithfileName);
using (var fileStream = new FileStream(uploadAbsolutePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
employee.ImageName = uploadPathWithfileName;
}
}
}
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Edit", new { id = employee.Id, name = employee.FirstName });
}
else
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
}
return View(employee);
}
i'm trying to integarte paypal api for sandbox testing account. i'm getting 400 bad request error when i try to get access token from the request code.
cshtml: Goto paypal
Js: function GetPaypal() {
window.location = "https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?client_id=clientid&response_type=code&scope=Email&redirect_uri=http://localhost:4427/";
}
C# code:
I am getting code using following code. :
public ActionResult Index(string code)
{
if (code != null)
{
string postcontents = string.Format("client_id={0}&client_secret={1}&grant_type=authorization_code&redirect_uri={2}&code={3}"
, System.Web.HttpUtility.UrlEncode("client_id")
, System.Web.HttpUtility.UrlEncode("Client Secret")
, System.Web.HttpUtility.UrlEncode("http://localhost:4427/")
, System.Web.HttpUtility.UrlEncode(code));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice");
request.Method = "POST";
byte[] postcontentsArray = System.Text.Encoding.UTF8.GetBytes(postcontents);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postcontentsArray.Length;
//OAuth.
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postcontentsArray, 0, postcontentsArray.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
string responseFromServer = reader.ReadToEnd();
reader.Close();
responseStream.Close();
response.Close();
// return SerializeToken(responseFromServer);
dynamic dynObj = JsonConvert.DeserializeObject(responseFromServer);
string token = dynObj["access_token"];
//token = ser.Deserialize<ImportContacts._Default.GoogleOAuthToken>(responseFromServer);
}
}
}
return View();
}
Please change Your CSHTML url as below:-
<script type="text/javascript">
function GetGmailContacts() {
window.location = "https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?client_id=clientid&response_type=code+id_token&scope=openid profile email&redirect_uri=localhost_url";
}
</script>
C# code:-
public ActionResult Index(string code,string id_token)
{
if (code != null)
{
string postcontents = string.Format("client_id={0}&client_secret={1}&grant_type=authorization_code&redirect_uri={2}&code={3}"
, System.Web.HttpUtility.UrlEncode("client_id")
, System.Web.HttpUtility.UrlEncode("Client Secret")
, System.Web.HttpUtility.UrlEncode(localhost_url)
, System.Web.HttpUtility.UrlEncode(code));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice");
request.Method = "POST";
byte[] postcontentsArray = System.Text.Encoding.UTF8.GetBytes(postcontents);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postcontentsArray.Length;
//OAuth.
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postcontentsArray, 0, postcontentsArray.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
string responseFromServer = reader.ReadToEnd();
reader.Close();
responseStream.Close();
response.Close();
// return SerializeToken(responseFromServer);
dynamic dynObj = JsonConvert.DeserializeObject(responseFromServer);
string token = dynObj["access_token"];
//token = ser.Deserialize<ImportContacts._Default.GoogleOAuthToken>(responseFromServer);
}
}
}
return View();
}
I hope it will work.
I can see parameters from js, but I can't use getParameter to get them. what's the problem?
js code
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var req = new XMLHttpRequest();
req.open("POST", "../PersonTest", true);
req.onreadystatechange = function(){
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseText);
} else {
alert("HTTP error " + req.status + ": " + req.statusText);
}
}
}
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.send("email=" + email + "&password=" + password);
servlet code
response.setContentType("text/xml;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//print request content
ServletInputStream is = request.getInputStream();
...
System.out.println(new String(baos.toByteArray(), "utf-8"));
//get parameter
String email = request.getParameter("email");
String password = request.getParameter("password");
System.out.println(email + " " + password);
}
servlet output:
email=123&password=123
null null
I have to display a treeview .But it will take much time, that's why I want to load this treeview on demand.At the first I want just display first level, and repeating that level by level.
This is the view
$("#onflycheckboxes").jstree({
json_data: {
"ajax": {
"url": function (node) {
var nodeId = "";
var url = ""
if (node == -1) {
url = "/TreeView/GetCollectionWS/source";
}
else {
nodeId = node.attr('id');
url = "/TreeView/GetCollectionWS/" + nodeId;
}
return url;
},
"type": "POST",
"dataType": "json",
"contentType": "application/json charset=utf-8"
}
},
checkbox: {
real_checkboxes: true,
checked_parent_open: true
},
plugins: ["themes", "json_data", "ui", "checkbox"]
});
this is the controller
public virtual ActionResult GetCollectionWS(string root)
{
int? nodeId = (root == source) ? (int?)null : Convert.ToInt32(root);
Object[] liste = new Object[100];
liste = DSClient.Views.Traitement.getTop(nodeId);
List<TreeViewNode> nodes = new List<TreeViewNode>();
for (int i = 0; (i < liste.Length && liste.ElementAt(i) != null);i++ )
{
bool leaf = false;
nodes.Add(new TreeViewNode()
{
id = Convert.ToString(DSClient.Views.Traitement.GetNodeId(liste.ElementAt(i))),
text = liste.ElementAt(i).Handle,
classes = leaf ? "file" : "folder",
hasChildren = !leaf
});
}
return Json(nodes);
}
when I try a breakpoint on the line return Json(nodes); I remarque that nodes contains
at the first {id=0,text=Collection-10,classes=folder,haChildren=false}
the view display nothing.Please, can any one help me??
public virtual string GetCollectionWS(string id)
{
Object[] liste = new Object[100];
client = new DSServiceClient();
if (id == "source")
{
Collection[] _top = new Collection[100];
client.Open();
_top = client.GetTopCollections();
client.Close();
for (int i = 0; i < _top.Length; i++)
{
DSClient.Controllers.Object obji = new DSClient.Controllers.Object();
obji.Handle = _top[i].Handle;
obji.Name = _top[i].Title;
liste[i] = obji;
}
}
else
{
client = new DSServiceClient();
client.Open();
Tree tree = client.GetTreeView(id);
client.Close();
liste = tree.listObjects;
}
var recursiveObjects = FillRecursive(liste);
string myjsonmodel = new JavaScriptSerializer().Serialize(recursiveObjects);
return myjsonmodel;
}
private static List<RecursiveObject> FillRecursive(Object[] flatObjects)
{
List<RecursiveObject> recursiveObjects = new List<RecursiveObject>();
for (int i = 0; (i < flatObjects.Length && flatObjects.ElementAt(i) != null); i++)
{
recursiveObjects.Add(new RecursiveObject()
{
data = flatObjects.ElementAt(i).Name,
id = flatObjects.ElementAt(i).Handle,
attr = new FlatTreeAttribute { id = flatObjects.ElementAt(i).Handle, selected = false },
children = null,
state = "closed"
});
}
return recursiveObjects;
}
Now I want to send the text and Id of nodes selected to my controller.
<script type="text/javascript">
var divId = [];
var divText = [];
$('#idjstree').value=function GetIDs() {
divId = [];
divText = [];
$("#onflycheckboxes").jstree("get_checked", null, true).each
(function () {
divId.push(this.id);
divText.push($(this).children('a').text());
});
return (divId);
}</script
and this is in the view
#:<div id="onflycheckboxes"></div>
#:<input type="hidden" id="idjstree" name="idjstree" value="" />
but always I get idjstree="" when I do a breakpoint on the post of create.But the function GetIDs() is correct.
What can I do please?
i stored few images in database in binary format, now i want to display those images in my view,how can we convert those images from binary format to image format again?
this is my action menthod in my controller
public ActionResult DislpayAllImage()
{
DataSet dsa = new DataSet();
dsa = objImage.getAllImages();
DataTable dt = new DataTable();
dt = dsa.Tables[0];
if (dt != null)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Byte[] image = (Byte[])dt.Rows[i]["UsImage"];
return File(image, "image/jpg");
}
}
return View();
}
this is my code in model
public DataSet getUserImage(int Id)
{
DataSet ds = new DataSet();
try
{
DbCommand db = dbcon.GetStoredProcCommand("GetImage");
dbcon.AddInParameter(db, "#Id", DbType.Int16, Id);
db.CommandType = CommandType.StoredProcedure;
return ds = dbconstr.ExecuteDataSet(dbCmd);
}
catch(Exception ex)
{
return ds = null;
}
}
view
#foreach( var image in ViewData.Images )
{
<img src="#Url.Action("DislpayImage", "Home",new { id = image.ImageID })" />
}
how can i display my image in razor view,also is the above code fine?
You need to call your Controller's Action(DislpayImage()) from the View like this:
<img src="<%= Url.Action("DislpayImage", "Controller") %>" alt="myimage" />
or
<img src="#Url.Action("DislpayImage", "Controller")" alt="myimage" />
Hope it helps you.
Edit
Just pass the id of the image you want to display to Controller action
public ActionResult DislpayImage(int id)
{
DataSet dsa = new DataSet();
dsa = objImage.getUserImage(id);
var imagedata = dsa.Tables[0].Columns["MyImage"];
return File(imagedata, "image/jpg");
}
Now pass the id of image which you want to display in your view, like this:
<img src="#Url.Action("DislpayImage", "Controller", new { id="2" })" alt="myimage" />
Now you will get the image with id as 2.
<% foreach( var image in ViewData.Images ) { %>
<%= Html.Image( Url.Action( "Show", "Image", new { id = image.ImageID } ) ) %>
<% } %>
public class ImageController : Controller
{
public void Show(string id)
{
Image image = GetImage(id);
Response.Buffer = True;
Response.Clear();
Response.ContentType = "image/gif";
Response.BinaryWrite( image.Data );
Response.End();
}
}
This response is just a copy of an answer from another forum.
This is not my own. I'm pasting it here to help you and someone else in this forum
with the same issue.
Here is the main link: http://forums.asp.net/post/2264885.aspx