搜尋
首頁後端開發php教程uploadFile+nginx實作上傳圖片(Windows/Linux皆可用)

       上傳圖片的功能想必並不是什麼費勁的事兒了,但大多數童鞋都是在本機(也是tomcat/jboss伺服器)實現上傳,且沒有考慮圖片重命名(中文亂碼)的問題。

       這篇部落格的上傳圖片是基於真實的項目,且採用了nginx圖片伺服器,Windows和Linux伺服器皆可使用。

       Jsp頁:需要一個file控件,一個hidden控件(用於建立自訂分類資料夾)和一個button(上傳按鈕)。

<div>
    	<p class="ui-tips">上传头像会自动生成头像缩略图片,您也可以拖动大图的裁剪区域,调整缩图内容。</p>
    	<p class="ui-tips">支持JPG、GIF、PNG等图片格式 推荐尺寸:180*180像素</p>
    	<input type="file" id="fileCoursePoster" style="display: none;" name="fileCoursePoster">
		<span id="errorCoursePoster" style="color: red; display: none;">请上传图片!</span>
	<input type="button" value="上传头像" class="btn btn-sm btn-normal">
	<input type="hidden" id="imageType" name="imageType"> 
</div>

       Js:需要引入ajaxfileupload這個js。

	function upLoad(){
		document.getElementById("imageType").value = "headPicture"; //图片分类,自定义类型,是海报还是个人头像
		$("#fileCoursePoster").click();
	}
	function uploadCoursePoster() {
		var imageType = document.getElementById("imageType").value;
		var studentId=$("#studentId").val();
		$.ajaxFileUpload({
			url : "/itoo-jrkj-student-web/media/uploadImages",		
			secureuri : false,
			data : {
				"studentId" : studentId,
				"imageType" : imageType
			},
			fileElementId : "fileCoursePoster",// 文件选择框的id属性
			dataType : 'json',
			success : function(data) {
				$("#imgCoursePoster").attr(
						"src",
						"http://123.56.120.25:8888/apple/"
								+ data);
				$('#headPic').val(data);
				alert("上传成功!");
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert("上传失败!");
			}
		});
	}

       Controller:

// 上传个人头像--生成图片路径并将路径保存到数据库
	@RequestMapping(value = "media/uploadImages", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public void uploadImages(HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException,
			IOException {
		// 上传到指定的文件夹中,imageType为文件夹的名字
		String imageType = request.getParameter("imageType").toString(); //文件夹名,便于图片分类
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
		String fileName = "";//图片的名字

		Calendar date = Calendar.getInstance(); //以图片类别+日期规划图片文件夹层级
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy");
		SimpleDateFormat format2 = new SimpleDateFormat("MM");
		SimpleDateFormat format3 = new SimpleDateFormat("dd");
		String year = format1.format(date.getTime());
		String month = format2.format(date.getTime());
		String day = format3.format(date.getTime());
		// 上传的图片存储的路径,格式如下:
		
//------------------要先将文件传入本机Jboss下的jboss3.1/bin文件夹中,因为File获得图片的绝对路径是自己定位到这儿了

		String uploadServicePath = "";
		String filePath="";
		for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
			String key = (String) it.next();
			MultipartFile mulfile = multipartRequest.getFile(key);
			fileName = mulfile.getOriginalFilename(); //获取上传图片的文件名,以便得到其在jboss中的路径
			//获取存在服务器下的图片的绝对路径
			File getFilePath=new File(fileName);//要根据图片名字获取路径
			filePath=getFilePath.getAbsolutePath();//获取Jboss服务器bin路径
			File file = new File(filePath);
			mulfile.transferTo(file);//保存
		}
		
		File imagefile = new File(filePath);  
        //TODO:创建ftp客户端  --读配置文件
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("GBK");  
        String hostname = "xxx.xxx.xxx.xxx";  //FTP服务器主机ip
        int port = 21;//FTP服务器端口,默认就是21
        String username = "apple";  //FTP服务器用户名(可以有多个)
        String password = "apple123";//FTP服务器密码
        try {  
            //链接ftp服务器  
            ftpClient.connect(hostname, port);  
            //登录ftp  
            ftpClient.login(username, password);  
            int reply = ftpClient.getReplyCode();    //ftp服务状态码
            System.out.println("reply返回码是:"+reply);
            
            //如果reply返回230就算成功了,如果返回530密码用户名错误或当前用户无权限。  
            if (!FTPReply.isPositiveCompletion(reply)) {    
                    ftpClient.disconnect();    
                    return ;    
                }    
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
                // 保存图片的相对路径到阿里云服务器
                fileName=UUID.randomUUID().toString()+".jpg";//自定义图片名,也能防止汉字的干扰
                uploadServicePath ="uploadImage/" + imageType + "/" + year + "/"
        				+ month+day+"/"+fileName; //上传到服务器的路径
                //在nginx上创建文件夹,一次只能创建一级,所以建多级要分多次
                ftpClient.makeDirectory("uploadImage");//什么的都不写的情况下,默认在root目录下创建文件夹,此处在nginx/apple/uploadImage下,apple文件夹是用户名,创建用户时自动建好的
                ftpClient.makeDirectory("uploadImage/"+imageType);
                ftpClient.makeDirectory("uploadImage/"+imageType+ "/" + year);
                ftpClient.makeDirectory("uploadImage/"+imageType+ "/" + year +"/"+month+day);  
                
                InputStream input = new FileInputStream(imagefile);   
                ftpClient.storeFile(uploadServicePath, input);//文件你若是不指定就会上传到root目录下
                input.close();    
                ftpClient.logout();   
              
        } catch (SocketException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }finally   
        {    
            if (ftpClient.isConnected())  
            {    
                try   
                {    
                    ftpClient.disconnect();    
                } catch (IOException ioe)   
                {    
                    ioe.printStackTrace();  
                }    
            }   
        }
		
		// 根据id更新个人信息
		Student student = new Student();
		String studentId = request.getParameter("studentId");
		student = studentBean.findStudentById(studentId, dataBaseName);
		student.setDataBaseName(dataBaseName);
		student.setHeadPic(uploadServicePath);
		if (!studentBean.updateHeadPicture(student)) {
			uploadServicePath = "error";
		}

		System.out.println("realPath-------------" + uploadServicePath);
		JacksonJsonUntil jacksonJsonUntil = new JacksonJsonUntil();
		jacksonJsonUntil.beanToJson(response, uploadServicePath);
	}

	// 读取往期图片
	@RequestMapping(value = "media/readImages", produces = "text/plain;charset=UTF-8")
	public void readImage(HttpServletRequest request,
			HttpServletResponse response) {
		// 或:从服务器中的相对位置读取图片
		// String imagesPath
		// =request.getSession().getServletContext().getRealPath("/")+request.getParameter("imagesPath");
		String imagesPath = request.getParameter("imagesPath");
		System.out.println("imagesPath-------------------" + imagesPath);
		try {
			File file = new File(imagesPath);
			if (file.exists()) {
				DataOutputStream temps = new DataOutputStream(
						response.getOutputStream());
				DataInputStream in = new DataInputStream(new FileInputStream(
						imagesPath));
				byte[] b = new byte[2048];
				while ((in.read(b)) != -1) {
					temps.write(b);
					temps.flush();
				}
				in.close();
				temps.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
               rrreee               

rrreee               有一個問題,即在上傳過程中,Eclipse中損壞常出現在兩個圖像中存在異常。懷疑是我把所有圖片都改為了JPG類型~ 還沒測試到底是不是。

         解決想法:在Controller裡判斷一下,截取原圖片名字的類型,即“.xxx”或“.xxxx”,如果不屬於jpg/jpeg/png/四種類型就不准上傳,符合的將其重命名後再加上它原本的圖片類型後綴。

         

🎜 以上就介紹了uploadFile+nginx實作上傳圖片(Windows/Linux皆可使用),包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。 🎜 🎜 🎜
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP的依賴注入:快速摘要PHP的依賴注入:快速摘要May 11, 2025 am 12:09 AM

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

提高PHP性能:緩存策略和技術提高PHP性能:緩存策略和技術May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具