我在手机上浏览文件并上传到服务器
我在“文件上传”中遇到了“我找不到文件”的问题。
.Net文件上传方法(服务器端代码)
Public Function UploadFiles(ByVal docs As Byte(), ByVal filename As String, ByVal UserId As Integer, ByVal PartnerId As Integer, ByVal IdeaId As Integer) As String
'Public Function UploadFiles(ByVal doctitle As String, ByVal docdescription As String, ByVal docs As Byte(), ByVal filename As String, ByVal UserId As Integer, ByVal UserType As String, ByVal IdeaId As Integer, ByVal PartnerId As Integer) As String
Dim NoOfDocs As Integer
Dim iCount As Integer
Dim sConId As String
Dim sConId1 As String
Dim sConId2 As String
Dim txtTitle As eCMSLib.Component.TextBox
Dim txtDesc As eCMSLib.Component.TextBox
Dim Upload1 As FileStream
Dim dirname As String
Dim strDocTitle As String = ""
Dim strDocDesc As String = ""
Dim dirconsultee As String
Dim createdirconsultee As String
Dim ServerPath As String
Dim ServerPath1 As String
Dim strFilename As String
Dim strOnlyFilename As String = ""
Dim objDoc As New Elegant.BusinessLogicLayer.DocumentAndResponse
Dim objIdea As New Ideas
Dim createdir As String
NoOfDocs = GetNumberOfUploadDocs(PartnerId)
Try
'---------------------------------------------------------------------------
'Create consultation directory
dirname = "Idea" & IdeaId
createdir = Server.MapPath("uploaddocs")
Dim dir As DirectoryInfo
Dim tempdir As String
tempdir = createdir & "\" & dirname
dir = New DirectoryInfo(tempdir)
If dir.Exists = True Then
Else
dir.Create()
End If
'---------------------------------------------------------------------------
'Create the consultee directory
dirconsultee = "Consultee" & UserId
'UserID = Integer.Parse(Session("UID_User"))
createdirconsultee = Server.MapPath("../uploaddocs/Idea" & IdeaId & "")
Dim dirconsultee1 As DirectoryInfo
Dim tempdir1 As String
tempdir1 = createdirconsultee & "\" & dirconsultee
dirconsultee1 = New DirectoryInfo(tempdir1)
If dirconsultee1.Exists = True Then
Else
dirconsultee1.Create()
End If
'---------------------------------------------------------------------------
NoOfDocs = 1
For iCount = 0 To NoOfDocs - 1
ServerPath = ""
ServerPath = Server.MapPath("../uploaddocs/" & dirname & "/" & dirconsultee & "")
ServerPath1 = dirname & "/" & dirconsultee
Directory.SetCurrentDirectory(ServerPath)
sConId = "m_txt_" & iCount & "_" & "UF" & iCount
'sConId1 = doctitle(iCount)
'sConId2 = docdescription(iCount)
'sConId1 = doctitle
'sConId2 = docdescription
Dim ms As New MemoryStream(docs)
'Dim fs As New System.IO.FileStream(dirname & "/" & dirconsultee & "/" & sConId, IO.FileMode.Create, System.IO.FileAccess.ReadWrite)
'ms.WriteTo(fs)
'ms.Close()
'fs.Close()
'fs.Dispose()
'Upload1 = fs
'txtTitle = CType(tbluploaddoc.FindControl(sConId1), eCMSLib.Component.TextBox)
'txtDesc = CType(tbluploaddoc.FindControl(sConId2), eCMSLib.Component.TextBox)
Dim fs As System.IO.FileStream
'If sConId1 <> "" Then
' strDocTitle = sConId1
'Else
' strDocTitle = ""
'End If
'If sConId2 <> "" Then
' strDocDesc = sConId2
'Else
' strDocDesc = ""
'End If
If docs IsNot Nothing Then
'If FileFieldSelected(Upload1) = True Then
strFilename = sConId
If strFilename <> String.Empty Then
strOnlyFilename = System.IO.Path.GetFileName(strFilename)
If Not eCMSLib.Common.Operation.CommonFunctions.isValidUserDefineFile(strOnlyFilename, ".doc,.docx,.pdf,.ppt,.pptx,.pps,.gif,.jpeg,.jpg,.bmp,.htm,.html") Then
'lblErroMsg.Visible = True
Dim strErroMsg As String = "Invalid File format. You can upload only files with.doc,.docx,.pdf,.ppt,.pptx,.pps,.gif,.jpeg,.jpg,.bmp,.htm,.html extesion."
'Return lblErroMsg.Text
'Return False
Context.Response.Write("{""Uploaddocs"":" & New JavaScriptSerializer().Serialize(strErroMsg) & "}")
End If
ServerPath = ServerPath & "/" & strOnlyFilename
ServerPath1 = dirname & "/" & dirconsultee & "/" & strOnlyFilename
'If Upload1.PostedFile.ContentLength > 15000000 Then
' 'lblErroMsg.Visible = True
' Dim strErroMsg As String = "File size is too large. Please try again."
' Context.Response.Write("{""Uploaddocs"":" & New JavaScriptSerializer().Serialize(strErroMsg) & "}")
' 'Return lblErroMsg.Text
' 'Exit Function
'End If
Dim bln As Boolean
bln = objDoc.IsFileExist(ServerPath1, UserId)
If bln = True Then
'lblErroMsg.Visible = True
Dim strErroMsg As String = "This file " & strOnlyFilename & "has already been uploaded."
Context.Response.Write("{""Uploaddocs"":" & New JavaScriptSerializer().Serialize(strErroMsg) & "}")
' Return lblErroMsg.Text
'Exit Function
End If
'--------------------------------------------------------------------------------------
Dim BLNUpload As Boolean = ValidationForUpload(UserId, IdeaId)
If BLNUpload = False Then
Dim UploadedFile As Integer
Dim objDocs1 As New DocumentAndResponse
UploadedFile = objDocs1.CountUplodedFileForIdeaUser(UserId, IdeaId)
'Dim strErroMsg As String = "Your documents " & UploadedFile & " have been uploaded ."
'Return lblErroMsg.Text
'Exit Function
End If
'--------------------------------------------------------------------------------------
'eCMSLib.Common.Operation.CommonFunctions.UploadFile(Upload1, ServerPath, 15000000)
fs = New System.IO.FileStream(dirname & "/" & dirconsultee & "/" & sConId, IO.FileMode.Create, System.IO.FileAccess.ReadWrite)
ms.WriteTo(fs)
ms.Close()
fs.Close()
fs.Dispose()
End If
'-------------------------------------------------------------------------------------------
'Insert Data in database for upload documents track.
Dim sPath As String
Dim DocRefNumber As String
Dim UploadFileContForUser As Integer
Dim objDocs2 As New DocumentAndResponse
UploadFileContForUser = objDocs2.CountUplodedFileForIdeaUser(UserId, IdeaId)
If iCount = 0 Then
DocRefNumber = IdeaId & "-" & UserId & "-" & Date.Now.Day & "-" & Date.Now.Month & "-" & Date.Now.Year & "-" & UploadFileContForUser + iCount + 1
Else
DocRefNumber = IdeaId & "-" & UserId & "-" & Date.Now.Day & "-" & Date.Now.Month & "-" & Date.Now.Year & "-" & UploadFileContForUser + 1
End If
sPath = dirname & "/" & dirconsultee & "/" & strOnlyFilename
Dim oInfo As Hashtable = New Hashtable
oInfo.Add("n_fkIdeaId", IdeaId)
oInfo.Add("t_DocPath", sPath)
oInfo.Add("n_UplodedTime", "getdate()")
oInfo.Add("n_fkUserID", UserId)
oInfo.Add("t_UserType", "Consultee")
oInfo.Add("t_DocType", System.IO.Path.GetExtension(strOnlyFilename))
oInfo.Add("t_DocSize", fs.Length)
oInfo.Add("t_DocRefNumber", DocRefNumber)
oInfo.Add("t_DocTitle", strDocTitle)
oInfo.Add("t_DocDesc", strDocDesc)
objDoc.AddIdeaDocument(oInfo)
'-------------------------------------------------------------------------------------------
'End If
End If
Next
Catch ex As Exception
''Throw ex
objIdea.DeleteIdea(IdeaId, PartnerId) 'Added by Pinki to resolve the issue when file is invalid - (28 apr 2011)
End Try
Return String.Empty
End Function
Public Function GetNumberOfUploadDocs(ByVal PartnerID As Integer) As Integer
Dim str As String
Dim Number As Integer
str = "SELECT ISNULL(paravaluedtl,'0') paravaluedtl from tblparameterdtl where fkparameterid='NoOFUpload_SubmittingIdea' and fkConsultPartnerID= " & PartnerID & " "
Number = eCMSLib.Common.Operation.DatabaseIntraction.GetSingleRowColumnValue(str)
Return Number
End Function
Public Function GetAllowUploadIdeaDocs(ByVal PartnerID As Integer) As String
Dim str As String
Dim strAllow As String
str = "SELECT paravaluedtl from tblparameterdtl where fkparameterid='EnableUpload_SubmittingIdea' and fkConsultPartnerID= " & PartnerID & " "
strAllow = eCMSLib.Common.Operation.DatabaseIntraction.GetSingleRowColumnValue(str)
Return strAllow
End Function
Public Function FileFieldSelected(ByVal FileField As System.Web.UI.HtmlControls.HtmlInputFile) As Boolean
' Returns a True if the passed
' FileField has had a user post a file
If FileField.PostedFile Is Nothing Then Return False
If FileField.PostedFile.ContentLength = 0 Then Return False
Return True
End Function
Public Function ValidationForUpload(ByVal UserID As Integer, ByVal IdeaID As Integer) As Boolean
Dim objUserDoc As New DocumentAndResponse
Dim bln As Boolean
bln = objUserDoc.GetFileUploadCountForIdeaUser(UserID, IdeaID, Session("ConsultPartner"))
Return bln
End Function
上传Android方法
/** android File upload start */
public static String doFileUpload(String path, String URL) {
final DataOutputStream dos;
String exiting_file_path = path;
Log.d("d file path--->", "" + path);
String boundary = "*****";
String twohypens = "--";
String lineend = "\r\n";
int maxBufferSize = 1 * 1024 * 1024;
int buferSize;
int bytesRead;
String url_string = URL;
try {
Log.d("Debug", "Start Uploading");
FileInputStream fileInStream = new FileInputStream(
exiting_file_path);
URL url = new URL(url_string);
httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("POST");
httpUrlConn.setRequestProperty("connection", "Keep-Alive");
httpUrlConn.setRequestProperty("content-type",
"multipart/form-data;boundary=" + boundary);
httpUrlConn.setRequestProperty("UserId", "" + SoapParsar.UserID);
httpUrlConn.setRequestProperty("PartnerId", ""
+ SoapParsar.PartnerID);
httpUrlConn.setRequestProperty("IdeaId", "" + 1400);
httpUrlConn.setRequestProperty("Path", "file://" + path);
dos = new DataOutputStream(httpUrlConn.getOutputStream());
dos.writeBytes(twohypens + boundary + lineend);
dos.writeBytes("content-disposition:form-data; name=\"upload_file\"; filename=\""
+ exiting_file_path + "\"" + lineend);
dos.writeBytes(lineend);
int buferAvailable = fileInStream.available();
buferSize = Math.min(buferAvailable, maxBufferSize);
final byte[] buffer = new byte[buferSize];
bytesRead = fileInStream.read(buffer, 0, buferSize);
// -------------------
if (isFromCamera) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Log.d("bit map hight", "--->" + resizedBitmap.getHeight());
Log.d("bit map width", "--->" + resizedBitmap.getWidth());
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
dos.write(byteArray, 0, byteArray.length);
} else {
while (bytesRead > 0) {
dos.write(buffer, 0, buferSize);
buferAvailable = fileInStream.available();
buferSize = Math.min(buferAvailable, maxBufferSize);
bytesRead = fileInStream.read(buffer, 0, buferSize);
}
}
// ---------------
dos.writeBytes(lineend);
dos.writeBytes(twohypens + boundary + twohypens + lineend);
fileInStream.close();
dos.flush();
dos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
DataInputStream inStream = new DataInputStream(
httpUrlConn.getInputStream());
STR1 = inStream.readLine();
while ((STRRRR = inStream.readLine()) != null) {
Log.d("Debug", "Server Response " + STRRRR);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
/** in STRRRR you get name of photo */
Log.d("File Uploded--->", "" + STR1);
return STR1;
}
按钮上传点击代码
btnPost.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String title = ni_title.getText().toString();
String detail = ni_detail.getText().toString();
String tag = ni_tag.getText().toString();
String directorate = ni_directorate.getText().toString();
String filepath = ni_filepath.getText().toString();
Log.d("local file path", "" + path + "/" + filepath);
boolean post_idea = true;
if (title.equalsIgnoreCase("")) {
ni_title.setError("Enter Title");
post_idea = false;
}
if (detail.equalsIgnoreCase("")) {
ni_detail.setError("Enter Descrebtion");
post_idea = false;
}
if (tag.equalsIgnoreCase("")) {
ni_tag.setError("Enter Tag");
post_idea = false;
}
if (directorate.equalsIgnoreCase("")) {
ni_directorate.setError("Enter Directorate");
post_idea = false;
}
// if(filepath.equalsIgnoreCase("")){
// ni_filepath.setError("select file");
// }
if (!Select_c) {
Toast.makeText(add_new_idea.this, "Select Category",
Toast.LENGTH_SHORT).show();
post_idea = false;
}
if (post_idea) {
try {
General_class.arrayPost.clear();
General_class.arrayPost.add(new BasicNameValuePair(
"IdeaId", "0"));
General_class.arrayPost.add(new BasicNameValuePair(
"ideaTitle", "" + title));
General_class.arrayPost.add(new BasicNameValuePair(
"ideadescription", "" + detail));
General_class.arrayPost.add(new BasicNameValuePair(
"SessionId", "0"));
General_class.arrayPost.add(new BasicNameValuePair(
"UserID", "" + SoapParsar.UserID));
General_class.arrayPost.add(new BasicNameValuePair(
"UserType", "" + SoapParsar.Usertype));
General_class.arrayPost.add(new BasicNameValuePair(
"emailid", "dhaval@elegantmicroweb.com"));
General_class.arrayPost.add(new BasicNameValuePair(
"PartnerID", "" + SoapParsar.PartnerID));
General_class.arrayPost.add(new BasicNameValuePair(
"tags", "" + tag));
General_class.arrayPost.add(new BasicNameValuePair(
"categoryids", "" + selected));
/*
* General_class.arrayPost.add(new BasicNameValuePair(
* "categoryids", "" + selected));
*/
// ni_filepath
String para = "?IdeaId=0&ideaTitle=" + title
+ "&ideadescription=" + detail
+ "&SessionId=0&UserID=" + SoapParsar.UserID
+ "&emailid=&UserType=" + SoapParsar.Usertype
+ "&PartnerID=" + SoapParsar.PartnerID
+ "&tags=" + tag + "&categoryids=" + selected;
// String Res = General_class
// .Call_Http_URL_PostMethod(SoapParsar.BASEURL_LOGIN
// + "/AddEditIdea");
String URL = SoapParsar.BASEURL_LOGIN + "/AddEditIdea"
+ para;
URL = General_class.replaceSpace(URL);
Log.e("URL--->", "" + URL);
String Res = General_class.GETMethod(URL);
Log.e("post idea-->", "" + Res);
/*
* General_class.doFileUpload(ni_filepath.getText()
* .toString(), SoapParsar.BASEURL_LOGIN +
* "/UploadFiles");
*/
/*
General_class.doFileUpload("" + path + "/" +ni_filepath.getText().toString(),
SoapParsar.BASEURL_LOGIN + "/UploadFiles");
*/
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
General_class.doFileUpload(path + "/" +
ni_filepath.getText().toString(),
SoapParsar.BASEURL_LOGIN + "/UploadFiles?UserId=" +
SoapParsar.UserID + "&PartnerId=" + SoapParsar.PartnerID
+ "&IdeaId=0&filename="
+ni_filepath.getText().toString());
Log.e("path---->111-->", "" + path);
/* General_class.doFileUpload("" + path + "/" +ni_filepath.getText().toString(),
SoapParsar.BASEURL_LOGIN + "/UploadFiles");*/
// General_class.doFileUpload(path + "/"+
// ni_filepath.getText().toString(),SoapParsar.BASEURL_LOGIN
// + "?op=UploadFiles");
} else {
Toast.makeText(add_new_idea.this, "enter all details",
Toast.LENGTH_SHORT).show();
}
}
});
错误日志:
URL--->(21331): http://10.0.0.230:81/samplewebservice/webservice.asmx/AddEditIdea?IdeaId=0&ideaTitle=kihgtff&ideadescription=bhhhjhhb&SessionId=0&UserID=430&emailid=&UserType=Consultee&PartnerID=9&tags=%20&categoryids=17
04-01 18:07:38.476: D/d file path--->(21331): /mnt/sdcard/Aaa.JPG
04-01 18:07:38.476: D/Debug(21331): Start Uploading
04-01 18:07:38.726: W/System.err(21331): java.io.FileNotFoundException: `http://10.0.0.230:81/samplewebservice/webservice.asmx/UploadFiles?UserId=430&PartnerId=9&IdeaId=0&filename=Aaa.JPG`
04-01 18:07:38.750: W/System.err(21331): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
04-01 18:07:38.750: W/System.err(21331): at com.idea_mobile.General_class.doFileUpload(General_class.java:640)
04-01 18:07:38.750: W/System.err(21331): at com.idea_mobile.add_new_idea$2.onClick(add_new_idea.java:238)
04-01 18:07:38.750: W/System.err(21331): at android.view.View.performClick(View.java:2485)
04-01 18:07:38.750: W/System.err(21331): at android.view.View$PerformClick.run(View.java:9080)
04-01 18:07:38.750: W/System.err(21331): at android.os.Handler.handleCallback(Handler.java:587)
04-01 18:07:38.750: W/System.err(21331): at android.os.Handler.dispatchMessage(Handler.java:92)
04-01 18:07:38.750: W/System.err(21331): at android.os.Looper.loop(Looper.java:130)
04-01 18:07:38.750: W/System.err(21331): at android.app.ActivityThread.main(ActivityThread.java:3687)
04-01 18:07:38.750: W/System.err(21331): at java.lang.reflect.Method.invokeNative(Native Method)
04-01 18:07:38.750: W/System.err(21331): at java.lang.reflect.Method.invoke(Method.java:507)
04-01 18:07:38.750: W/System.err(21331): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
04-01 18:07:38.750: W/System.err(21331): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
04-01 18:07:38.750: W/System.err(21331): at dalvik.system.NativeStart.main(Native Method)
04-01 18:07:38.750: D/File Uploded--->(21331): null
04-01 18:07:38.750: E/path---->111-->(21331): /mnt/sdcard
它给我文件不在这一行:
DataInputStream inStream = new DataInputStream(
httpUrlConn.getInputStream());
答案 0 :(得分:0)
不要使用客户端来读取文件,这似乎是你想要做的。
就我个人而言,我的上传方法签名有以下几点:
//Server
public void UploadFile(bytes[] file, string name)
{
//Store the BLOB object
}
//Client
public void SendFile()
{
var bytes = File.ReadAllBytes("Filename");
UploadFile(bytes, new FileInfo("Filename").Name);
}
请注意,您已经在C#
中完全标记了您的问题,这就是我给出的答案,如果您需要转换它,请使用online convertor。